Module using python psutil

Although you can also view the api documentation, but also turn around.

Original Address: https://blog.csdn.net/cpongo5/article/details/88820174

psutil (python system and process utilities) is a third-party library cross-platform, can easily get the process of system operation and system utilization (including expansion of CPU, memory, disk, network, etc.) information. It is mainly used for system monitoring, analysis, restriction managing system resources and processes. 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 supported operating systems including: Linux, Windows, macOS ,, AIX, and so on. Supports python2 and python3 version, the current latest version is 5.4.8.

1. psutil installation
. 1
PIP psutil the install
2. psutil CPU performance information acquiring system of
2.1. Cpu_times CPU runtime
psutil.cpu_times (percpu = False) the CPU operation time of each particular state is returned as a tuple.

CPU operating state explained
user processes executing user mode code is consuming CPU time.
The percentage nice at high priority level user to perform CPU usage.
kernel system call execution system CPU time used.
percentage of idle CPU is idle and the system no outstanding disk I / O request.
iowait CPU waiting for I / O input and output time
irq CPU hardware interrupts for maintaining the percentage of time spent.
softirq CPU for software interrupt service time it takes a percentage.
steal time other operating systems running in a virtual environment takes
guest CPU for running virtual processor time percentage.
dpc deferred procedure call service time spent
time interrupt hardware interrupt service takes
. 1
2
. 3
. 4
. 5
. 6
. 7
. 8
. 9
10
. 11
12 is
13 is
14
15
16
. 17
18 is
. 19
20 is
## Ubuntu system
### acquires time information executed by the CPU

>>> import psutil
>>> psutil.cpu_times()
scputimes(user=42.85, nice=4.64, system=40.27, idle=4864.93, iowait=5.94, irq=0.0, softirq=2.16, steal=0.0, guest=0.0, guest_nice=0.0)


### acquires information for each logical CPU

>>> psutil.cpu_times(percpu=True)
[scputimes(user=13.2, nice=1.74, system=13.84, idle=2712.55, iowait=1.62, irq=0.0, softirq=0.57, steal=0.0, guest=0.0, guest_nice=0.0),
scputimes(user=10.48, nice=0.87, system=10.49, idle=2719.36, iowait=1.45, irq=0.0, softirq=0.21, steal=0.0, guest=0.0, guest_nice=0.0),
scputimes(user=12.4, nice=1.36, system=10.22, idle=2721.21, iowait=1.37, irq=0.0, softirq=0.7, steal=0.0, guest=0.0, guest_nice=0.0),
scputimes(user=11.28, nice=0.65, system=9.2, idle=2723.23, iowait=1.5, irq=0.0, softirq=0.83, steal=0.0, guest=0.0, guest_nice=0.0)]

## windows operating system

Psutil.cpu_times >>> ()
scputimes (User = 10006.453125, System = 5947.421875, IDLE = 155,528.3125, interrupt = 209.296875, DPC = 187.203125)
2.2. Cpu_percent CPU utilization
psutil.cpu_percent (interval = None, percpu = False) Returns a a floating point number current system CPU utilization percentage range. If interval = 0.1, represents the average utilization rate of 0.1sCPU. If the interval = 0 or None, since the last call to compare module or CPU time introduced through the system returns immediately. All data returned for the first time is a meaningless data. When percpu True is returned list showing the utilization of a float, expressed as a percentage for each logical CPU.

. 1
2
. 3
. 4
. 5
. 6
. 7
. 8
. 9
10
. 11
# and the time elapsed since the last call of cpu utilization
>>> psutil.cpu_percent ()
1.3

# Cpu in current usage rate 1s
>>> psutil.cpu_percent (= interval The. 1)
0.3

## four logical cpu utilization
>>> psutil.cpu_percent (interval The =. 1, percpu = True)
[1.0, 1.0, 0.0, 0.0]
2.3. Cpu_times_percent specific state of the CPU utilization
psutil.cpu_times (percpu = True) providing each particular utilization percentage of CPU time. percpu meaning icpu_percent interval and parameters of the same meaning as in ().

. 1
2
>>> psutil.cpu_times_percent (= interval The. 1)
scputimes (User = 0.0, Nice = 0.0, 0.5 = System, IDLE = 99.5, iowait = 0.0, IRQ = 0.0, softirq = 0.0, Steal = 0.0, 0.0 = Guest , guest_nice = 0.0)
2.4. cpu_count CPU number
psutil.cpu_count () returns the number of physical or logical CPU number of logic systems.

. 1
2
. 3
. 4
. 5
. 6
. 7
. 8
. 9
10
## Windows operating system virtual machine VM to two dual-core single-core processor
### the number of logical CPU
>>> psutil.cpu_count ()
. 8
### physical CPU number
> psutil.cpu_count >> (Logical = False)
. 4
### cpu number of currently available
>>> len (psutil.Process (). cpu_affinity ())
. 8
2.5. cpu_stats CPU statistics
cpu_stats () of various CPU statistics be returned tuple form.

CPU information interpretation
switching times after ctx_switches context startup
interrupts interrupts since boot
software since the number of interruptions soft_interrupts bootstrap
system since the number of calls syscalls bootstrapping
. 1
2
. 3
. 4
. 5
. 6
. 7
. 8
## Ubuntu system

>>> psutil.cpu_stats()
scpustats(ctx_switches=4589481, interrupts=2532478, soft_interrupts=719197, syscalls=0)

## windows system
>>> psutil.cpu_stats ()
scpustats (ctx_switches = 344 724 592, 270 222 602 = interrupts, soft_interrupts = 0, syscalls = 1,234,130,591)
2.6. Cpu_freq CPU frequency
psutil.cpu_freq (percpu = False) to return the package name, the CPU frequency , including the current expressed in Mhz, minimum and maximum frequencies. If percpu is True and retrieval system supports every CPU frequency, for the frequency of each CPU returns a list, or returns a list containing a single element (support only linux system). If unable to determine the minimum and maximum values, they are set to 0. Linux real-time reports on the current frequency value, on all other platforms it represents the maximum value.

. 1
2
. 3
. 4
. 5
. 6
. 7
. 8
. 9
10
. 11
## Windows System

>>> psutil.cpu_freq()
scpufreq(current=2594.0, min=0.0, max=2594.0)
>>> psutil.cpu_freq(percpu=False)
scpufreq(current=2594.0, min=0.0, max=2594.0)


WMIC: the root \ CLI> CPU List Brief
the DeviceID Manufacturer MaxClockSpeed
the CPU0 GenuineIntel 2594
. 3 psutil acquisition system memory performance information of
3.1 virtual_memory () of physical memory usage.
Memory information interpreter
total total physical memory
available to enter without the system memory immediately available under the SWAP .
percent share use of memory
used physical memory used by
the physical memory is not free to use
active or are in the most recently used physical memory
memory unused labeled inactive
cache buffers buffers used for
caching cached ccached use
shared displaying the shared physical memory the size of the
slab buffer kernel data structures
. 1
2
. 3
. 4
. 5
. 6
. 7
. 8
. 9
#windows

>>> psutil.virtual_memory()
svmem(total=8473522176, available=1940721664, percent=77.1, used=6532800512, free=1940721664)

#Linux

Psutil.virtual_memory >>> ()
svmem (Total = 2,070,257,664, = 777 777 152 Available, Percent = 62.4, Used = 1,090,142,208, Free = 80,498,688, Active = 1,195,728,896, inactive = 459 780 096, 164 036 608 = buffers, cached = 735 580 160, Shared = 10,145,792, = 221 949 952 the slab)
3.2. swap_memory () swap memory usage
. 1
2
. 3
. 4
. 5
. 6
. 7
. 8
. 9
10
. 11
SiN and sout on #Windows always set to 0

>>> psutil.swap_memory()
sswap(total=10151243776, used=7573495808, free=2577747968, percent=74.6, sin=0, sout=0)

#Linux
# SiN: integrated system from a disk bytes swapped
#sout: total system change number of bytes from the disk

Psutil.swap_memory >>> ()
sswap (Total = 2144333824, Used = 7,090,176, Free = 2,137,243,648, Percent = 0.3, SiN = 0, Sout = 6705152)
. 4 psutil obtain system performance information of the disk
4.1. Disk_partitions get all disk information
. 1
2
. 3
. 4
. 5
. 6
. 7
. 8
. 9
10
. 11
12 is
#windows

>>> from psutil import *
>>> disk_partitions()
[sdiskpart(device='C:\\', mountpoint='C:\\', fstype='NTFS', opts='rw,fixed'), #固态硬盘
sdiskpart(device='D:\\', mountpoint='D:\\', fstype='FAT32', opts='rw,removable'), #U盘
sdiskpart(device='E:\\', mountpoint='E:\\', fstype='', opts='cdrom')] #光盘

#Linux

Psutil.disk_partitions >>> ()
[sdiskpart (Device = '/ dev / sda1', the mountpoint = '/', FStype = 'ext4', the opts = 'RW, the relatime, the remount-errors = RO')]
4.2. Disk_usage obtaining information of a single disk
. 1
2
. 3
. 4
. 5
. 6
. 7
. 8
. 9
10
. 11
12 is
# Windows

>>> disk_usage('C:\\')
sdiskusage(total=126491697152, used=86524149760, free=39967547392, percent=68.4)
>>> disk_usage('D:\\')
sdiskusage(total=134184173568, used=1953497088, free=132230676480, percent=1.5)
>>> disk_usage('E:\\')
PermissionError: [WinError 21] 设备未就绪。

# linux
>>> psutil.disk_usage("/dev/sda1")
sdiskusage(total=1016070144, used=0, free=1016070144, percent=0.0)
4.3. psutil.disk_io_counters 获取IO信息
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
# If each physical disk perdisk for the installation of the system on True return information

# widows

>>> disk_io_counters()
sdiskio(read_count=870403, write_count=665904, read_bytes=36953495552, write_bytes=20282217984, read_time=1565, write_time=871)

#linux

Psutil.disk_io_counters >>> ()
sdiskio (read_count = 53366, the number of reads #
write_count = 9803, # write count
read_bytes = 709110784, # number of bytes read
write_bytes = 417996800, # number of bytes written
read_time = 29572, # reading time
write_time = 4656, # write time
read_merged_count = 1034, the number of combined read #
write_merged_count = 10158, the number of combined write #
busy_time = 17792 # actually do I / 0 operation time
)
. 5 psutil acquisition system performance the network information
5.1. psutil.net_connections acquiring network socket
. 1
2
. 3
. 4
. 5
. 6
. 7
. 8
. 9
10
. 11
12 is
13 is
#windows
>>> net_connections ()
[sconn(fd=-1, family=<AddressFamily.AF_INET6: 23>, type=1, laddr=addr(ip='::', port=1536), raddr=(), status='LISTEN', pid=724),
sconn(fd=-1, family=<AddressFamily.AF_INET: 2>, type=2, laddr=addr(ip='::1', port=5353), raddr=(), status='NONE', pid=4208),
sconn(fd=-1, family=<AddressFamily.AF_INET: 2>, type=2, laddr=addr(ip='0.0.0.0', port=58044), raddr=(), status='NONE', pid=14420),
sconn(fd=-1, family=<AddressFamily.AF_INET: 2>, type=1, laddr=addr(ip='127.0.0.1', port=36600), raddr=(), status='LISTEN', pid=6116),
sconn(fd=-1, family=<AddressFamily.AF_INET6: 23>, type=1, laddr=addr(ip='::1', port=26672), raddr=addr(ip='::1', port=35432))]


#Linux

Psutil.net_connections >>> ()
[sConn (FD =. 6, Family = 2, type = 2, LADDR = addr (IP = '0.0.0.0', Port = 68), RADDR = (), Status = 'NONE' , pid = 652)]
information 5.2. psutil.net_if_addrs acquisition card
. 1
2
. 3
. 4
. 5
. 6
. 7
. 8
. 9
10
. 11
# Windows

>>> net_if_addrs()
{'VMware Network Adapter VMnet1': [snicaddr(family=<AddressFamily.AF_LINK: -1>, address='00-50-56-C0-00-01', netmask=None, broadcast=None, ptp=None), snicaddr(family=<AddressFamily.AF_INET: 2>, address='192.168.153.1', netmask='255.255.255.0', broadcast=None, ptp=None), snicaddr(family=<AddressFamily.AF_INET6: 23>, address='fe80::4192:c5d1:8fff:98c6', netmask=None, broadcast=None, ptp=None)],
'VMware Network Adapter VMnet8': [snicaddr(family=<AddressFamily.AF_LINK: -1>, address='00-50-56-C0-00-08', netmask=None, broadcast=None, ptp=None), snicaddr(family=<AddressFamily.AF_INET: 2>, address='192.168.78.1', netmask='255.255.255.0', broadcast=None, ptp=None), snicaddr(family=<AddressFamily.AF_INET6: 23>, address='fe80::40d2:696a:cacb:8388', netmask=None, broadcast=None, ptp=None)],
'Loopback Pseudo-Interface 1': [snicaddr(family=<AddressFamily.AF_INET: 2>, address='127.0.0.1', netmask='255.0.0.0', broadcast=None, ptp=None), snicaddr(family=<AddressFamily.AF_INET6: 23>, address='::1', netmask=None, broadcast=None, ptp=None)]}

#linux
>>> psutil.net_if_addrs()
{'lo': [snicaddr(family=2, address='127.0.0.1', netmask='255.0.0.0', broadcast=None, ptp=None), snicaddr(family=10, address='::1', netmask='ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff', broadcast=None, ptp=None), snicaddr(family=17, address='00:00:00:00:00:00', netmask=None, broadcast=None, ptp=None)],
'eth0': [snicaddr(family=2, address='192.168.78.139', netmask='255.255.255.0', broadcast='192.168.78.255', ptp=None), snicaddr(family=10, address='fe80::20c:29ff:fef4:4e44%eth0', netmask='ffff:ffff:ffff:ffff::', broadcast=None, ptp=None), snicaddr(family=17, address='00:0c:29:f4:4e:44', netmask=None, broadcast='ff:ff:ff:ff:ff:ff', ptp=None)]}
5.3. psutil.net_if_stats acquired network interface state . 6. 5. 4. 32
. 1





7
8
9
10
11
12
13
14
15
16
# windows

>>> net_if_stats()
{'以太网': snicstats(isup=True, duplex=<NicDuplex.NIC_DUPLEX_FULL: 2>, speed=1000, mtu=1500),
'VMware Network Adapter VMnet1': snicstats(isup=True, duplex=<NicDuplex.NIC_DUPLEX_FULL: 2>, speed=100, mtu=1500),
'VMware Network Adapter VMnet8': snicstats(isup=True, duplex=<NicDuplex.NIC_DUPLEX_FULL: 2>, speed=100, mtu=1500),
'Loopback Pseudo-Interface 1': snicstats(isup=True, duplex=<NicDuplex.NIC_DUPLEX_FULL: 2>, speed=1073, mtu=1500),
'WLAN': snicstats(isup=False, duplex=<NicDuplex.NIC_DUPLEX_FULL: 2>, speed=0, mtu=1500),
'本地连接* 2': snicstats(isup=False, duplex=<NicDuplex.NIC_DUPLEX_FULL: 2>, speed=0, mtu=1500),
'本地连接* 1': snicstats(isup=False, duplex=<NicDuplex.NIC_DUPLEX_FULL: 2>, speed=0, mtu=1500)}
>>>

# Linux

Psutil.net_if_stats >>> ()
{ 'LO': snicstats (ISUP = True, 0 = Duplex, 0 = Speed, MTU = 65536), 'eth0': snicstats (ISUP = True, Duplex = 2, Speed = 1000, = 1500 MTU)}
5.4. psutil.net_io_counters acquiring traffic network port
. 1
2
. 3
. 4
. 5
. 6
. 7
. 8
. 9
10
. 11
12 is
13 is
14
15
16
. 17
# psutil.net_io_counters (pernic = False) if pernic is installed on each system True network interfaces return information.
# Windows

Net_io_counters >>> ()
snetio (bytes_sent = 176 300 623, # of bytes sent
bytes_recv = 402338143, # the received byte
packets_sent = 2509858, # Number of transmitted packets
packets_recv = 713322, # receiving packet number
errin = 0, # receiving errors
errout = 0, # transmission errors
dropin = 0, # discarding the incoming packet number
dropout = 0) # number of packets discarded outgoing


# the Linux
>>> psutil.net_io_counters ()
snetio (bytes_sent = 83 801, bytes_recv = 31,649,461, packets_sent = 1277, packets_recv = 21180, ERRIN = 0, ERROUT = 0, = 0 DROPIN, Dropout = 0)
. 6 psutil get additional information about the performance of the system
6.1. acquisition starting time
. 1
2
. 3
>>> Import datetime, psutil
>>> datetime. datetime.fromtimestamp (psutil.boot_time ()) the strftime. ( "% D%% Y-M-% H:% M:% S")
'2018-11-09 15:01:10'
6.2.Get the current user
1
2
>>> psutil.users()
[suser(name='root', terminal=None, host='0.4.0.0', started=1541862557.0, pid=None)]
6.3. 获取PID
1
2
>>> psutil.pids()
[0, 4, 120, 404, 592, 724, 796, 816, 936, 964, 972, 344, 496, 1180, 1336, 1508, 1540, 1568, 1592, 1644, 1696, 1720]
6.4. 获取进程信息
1
2
3
4
5
6
>>> for x in psutil.process_iter():
... print(x)
...
psutil.Process(pid=592, name='csrss.exe', started='2018-11-09 15:01:18')
psutil.Process(pid=724, name='wininit.exe', started='2018-11-09 15:01:24')
psutil.Process(pid=736, name='svchost.exe', started='2018-11-10 17:20:13')

---------------------
Disclaimer: This article, "insisted 669" original article is CSDN bloggers, follow CC 4.0 by-sa copyright agreements, please attach a reprint the original source link and this statement.
Original link: https: //blog.csdn.net/cpongo5/article/details/88820174

Guess you like

Origin www.cnblogs.com/linwenbin/p/11363796.html