Introduction of psutil python

A, psutil modules:

1.psutil is a cross-platform library ( http://pythonhosted.org/psutil/ ) can easily process and system utilization acquisition system operation (including CPU, memory, disk, network, etc.) information. It is mainly used for system monitoring, performance analysis, process management. It implements the functions of the same command-line tools, such as ps, top, lsof, netstat, ifconfig, who, df, kill, free, nice, ionice, iostat, iotop, uptime, pidof, tty, taskset, pmap and so on. Currently supports 32-bit and 64-bit Linux, Windows, OS X, FreeBSD and Sun Solaris and other operating systems.

2. Installation psutil modules:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
CentOS安装psutil包:
python版本: 3.5
 
wget https: / / pypi.python.org / packages / source / p / psutil / psutil - 3.2 . 1.tar .gz  - - no - check - certificate
tar zxvf psutil - 3.2 . 1.tar .gz
cd psutil - 3.2 . 1
python setup.py install
 
Windos安装psutil包:
 
D:\python35\Scripts>pip3.exe install psutil
Collecting psutil
   Downloading psutil - 5.3 . 1 - cp35 - cp35m - win_amd64.whl ( 215kB )
     100 %  |████████████████████████████████|  225kB  84kB / s
Installing collected packages: psutil
Successfully installed psutil - 5.3 . 1

 Second, using the system to obtain basic information:

1.CPU information

Use cpu_times complete cpu information obtaining method, as shown below.

>>>import psutil
>>>psutil.cpu_times() scputimes(user=650613.02, nice=22.14, system=154916.5, idle=16702285.26, iowait=68894.55, irq=3.38, softirq=7075.65, steal=0.0, guest=0.0) >>>

A single data acquisition, such as the user's waiting time cpu or io, as follows:

>>> psutil.cpu_times().user
650617.11
>>> psutil.cpu_times().iowait
68894.63
>>> 

 Get the number of logical and physical cpu, the default logical value is True.

Copy the code
The number of logical #CPU 
>>> psutil.cpu_count () 
2 
#CPU number of physical 
>>> psutil.cpu_count (Logical = False) 
. 1 
>>> 
#percent () has two parameters, the first one of percpu (default false, total occupancy; True occupied respectively) second interval The (time interval)

 

Copy the code

Get cpu usage:

>>> psutil.cpu_percent()
2.5
>>> psutil.cpu_percent(1)
2.5
>>> 

 >>> psutil.cpu_percent(True,1)
 [1.5, 0.0, 1.5, 0.0, 3.1, 0.0, 3.1, 0.0]

 

import psutil
if __name__ == '__main__':
print(psutil.cpu_percent(percpu=True,interval=1))

2. Memory Information

Get memory information is mainly used virtual_memory method. using the method to use swap_memory swap.

Copy the code
>>> mem = psutil.virtual_memory()
>>> mem
svmem(total=4018601984, available=1066205184, percent=73.5, used=3904004096, free=114597888, active=3302174720, inactive=426078208, buffers=156520448, cached=795086848)
>>> mem.total
4018601984
>>> mem.used
3904004096
>>> mem.free
114597888#默认单位字节
>>> print(mem.total/1024/1024)
3832.4375
>>> 
Copy the code

Wherein the percent proportion represents the actual memory already in use, i.e., (1047543808-717537280) / 1047543808 * 100%. available memory representation can also be used.

 3. Disk Information

Disk Information has two parts, one is the disk utilization, one is io, they are available through disk_usage and disk_io_counters method.

First get the following partition information, and then look at the use of root partition:

Copy the code
>>> psutil.disk_partitions()
[sdiskpart(device='/dev/mapper/root', mountpoint='/', fstype='ext4', opts='rw,errors=remount-ro'), sdiskpart(device='/dev/sda1', mountpoint='/boot', fstype='ext2', opts='rw')]
>>> psutil.disk_usage('/')
sdiskusage(total=42273669120, used=17241096192, free=22885195776, percent=40.8)
>>> 
Copy the code

The default method for obtaining disk_io_counters io is the total number of hard disk and read and write information, and if necessary read and write information acquired io single partition plus "perdisk = True" parameter.

Copy the code
>>> psutil.disk_io_counters()
sdiskio(read_count=638190, write_count=77080153, read_bytes=16037795840, write_bytes=1628871606272, read_time=2307367, write_time=1777841305)
>>> psutil.disk_io_counters(perdisk=True)
{'vdb1': sdiskio(read_count=312, write_count=0, read_bytes=1238016, write_bytes=0, read_time=95, write_time=0), 'vda1': sdiskio(read_count=637878, write_count=77080257, read_bytes=16036557824, write_bytes=1628873314304, read_time=2307272, write_time=1777841879)}
>>> 
Copy the code

4. Network Information:

 Network and disk io io use similar methods mainly used net_io_counters, if needed io obtain information for a single network card, plus pernic = True parameter.

Copy the code
# Get the network overall io 
>>> 
>>> psutil.net_io_counters () 
snetio (bytes_sent = 525 490 132 009, 409 145 642 892 = bytes_recv, packets_sent = 948 527 563, 778 182 181 = packets_recv, ERRIN = 0, 0 = ERROUT, DROPIN = 0, = Dropout 0) 
# acquired card io where 
>>> 
>>> psutil.net_io_counters (pernic = True) 
{ 'LO': snetio (bytes_sent = 56,524,704,027, 56,524,704,027 = bytes_recv, packets_sent = 33,602,236, 33,602,236 = packets_recv, ERRIN = 0, ERROUT = 0, dropin = 0, dropout = 0), 'eth0': snetio (bytes_sent = 468966480940, bytes_recv = 352622081327, packets_sent = 914930488, packets_recv = 744583332, errin = 0, errout = 0, dropin = 0, dropout = 0) } 
>>>
Copy the code

The other system information:

1. Obtain boot time

Copy the code
## returns linux time format, converts the time stamp may be used 
>>> psutil.boot_time ()     
1496647567.0 

# converted into a time format NATURAL 
>>> psutil.boot_time () 
1496647567.0 
>>> datetime.datetime.fromtimestamp (psutil.boot_time ( )) the strftime (. "% Y-M-% D%% H:% M:% S") 
'2017-06-05 15: 26 is: 07' 
>>>
Copy the code

2. Check the system processes all

Copy the code
>>> psutil.pids()
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 46, 47, 48, 49, 50, 51, 52, 53, 60, 61, 63, 64, 65, 97, 98, 279, 280, 331, 398, 481, 676, 693, 769, 845, 848, 1023, 1085, 1108, 1355, 1366, 1457, 1474, 1475, 1494, 1541, 1543, 1545, 1546, 1548, 1550, 1552, 2829, 12436, 12913, 13129, 16022, 16029, 16030, 16031, 16032, 16033, 16518, 16520, 17088, 17124, 19203, 25382, 32679]
Copy the code

3. View a single process

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
=  psutil.Process( 16031 )
p.name()       #进程名
p.exe()          #进程的bin路径
p.cwd()         #进程的工作目录绝对路径
p.status()      #进程状态
p.create_time()   #进程创建时间
p.uids()       #进程uid信息
p.gids()       #进程的gid信息
p.cpu_times()     #进程的cpu时间信息,包括user,system两个cpu信息
p.cpu_affinity()   #get进程cpu亲和度,如果要设置cpu亲和度,将cpu号作为参考就好
p.memory_percent()   #进程内存利用率
p.memory_info()     #进程内存rss,vms信息
p.io_counters()     #进程的IO信息,包括读写IO数字及参数
p.connectios()     #返回进程列表
p.num_threads()   #进程开启的线程数
听过psutil的Popen方法启动应用程序,可以跟踪程序的相关信息
from  subprocess  import  PIPE
=  psutil.Popen([ "/usr/bin/python" "-c" "print('hello')" ],stdout = PIPE)
p.name()
p.username()

 查看系统硬件脚本:

#!/usr/bin/env python
 2 #coding:utf-8
 3 
 4 import psutil
 5 import datetime
 6 import time
 7 
 8 # 当前时间
 9 now_time = time.strftime('%Y-%m-%d-%H:%M:%S', time.localtime(time.time()))
10 print(now_time)
11 
12 # 查看cpu物理个数的信息
13 print(u"物理CPU个数: %s" % psutil.cpu_count(logical=False))
14 
15 #CPU的使用率
16 cpu = (str(psutil.cpu_percent(1))) + '%'
17 print(u"cup使用率: %s" % cpu)
18 
19 #查看内存信息,剩余内存.free  总共.total
20 #round()函数方法为返回浮点数x的四舍五入值。
21 
22 free = str(round(psutil.virtual_memory().free / (1024.0 * 1024.0 * 1024.0), 2))
23 total = str(round(psutil.virtual_memory().total / (1024.0 * 1024.0 * 1024.0), 2))
24 memory = int(psutil.virtual_memory().total - psutil.virtual_memory().free) / float(psutil.virtual_memory().total)
25 print(u"物理内存: %s G" % total)
26 print(u"剩余物理内存: %s G" % free)
27 print(u"物理内存使用率: %s %%" % int(memory * 100))
28 # 系统启动时间
29 print(u"系统启动时间: %s" % datetime.datetime.fromtimestamp(psutil.boot_time()).strftime("%Y-%m-%d %H:%M:%S"))
30 
31 # 系统用户
32 users_count = len(psutil.users())
33 #
34 # >>> for u in psutil.users():
35 # ...   print(u)
36 # ...
37 # suser(name='root', terminal='pts/0', host='61.135.18.162', started=1505483904.0)
38 # suser(name='root', terminal='pts/5', host='61.135.18.162', started=1505469056.0)
39 # >>> u.name
40 # 'root'
41 # >>> u.terminal
42 # 'pts/5'
43 # >>> u.host
44 # '61.135.18.162'
45 # >>> u.started
46 # 1505469056.0
47 # >>>
48 
49 users_list = ",".join([u.name for u in psutil.users()])
50 print(u"当前有%s个用户,分别是 %s" % (users_count, users_list))
51 
52 #网卡,可以得到网卡属性,连接数,当前流量等信息
53 net = psutil.net_io_counters()
54 bytes_sent = '{0:.2f} Mb'.format(net.bytes_recv / 1024 / 1024)
55 bytes_rcvd = '{0:.2f} Mb'.format(net.bytes_sent / 1024 / 1024)
56 print(u"网卡接收流量 %s 网卡发送流量 %s" % (bytes_rcvd, bytes_sent))
57 
58 io = psutil.disk_partitions()
59 # print(io)
60 # print("io[-1]为",io[-1])
61 #del io[-1]
62 
63 print('-----------------------------磁盘信息---------------------------------------')
64 
65 print("系统磁盘信息:" + str(io))
66 
67 for i in io:
68     o = psutil.disk_usage(i.device)
69     print("总容量:" + str(int(o.total / (1024.0 * 1024.0 * 1024.0))) + "G")
70     print("已用容量:" + str(int(o.used / (1024.0 * 1024.0 * 1024.0))) + "G")
71     print("可用容量:" + str(int(o.free / (1024.0 * 1024.0 * 1024.0))) + "G")
72 
73 print('-----------------------------进程信息-------------------------------------')
74 # 查看系统全部进程
75 for pnum in psutil.pids():
76     p = psutil.Process(pnum)
77 print (u "process name% -20s% -18s process memory usage status% -10s Created% -10s" \ 
78% (p.name (), p.memory_percent (), p.status (), the p- .create_time ()))

 

 

These are a few methods psutil linux system module obtaining basic information, about these common data. Of course, there are many other uses, the details can refer to his official documents.

URL: http://pythonhosted.org/psutil/

    http://www.cnblogs.com/liu-yao/p/5678157.html

   http://www.sijitao.net/2043.html

      http://www.cnblogs.com/luomingchuan/p/3777269.html

   http://www.sijitao.net/2016.html

 

  

Guess you like

Origin www.cnblogs.com/abels0025/p/11294724.html