Detailed explanation of psutil library developed by Python Operation and maintenance
- 2020-12-19 21:07:51
- OfStack
introduce
psutil makes it easy to capture the process and system utilization of a running system.
The import module
import psutils
Get system performance information
CPU information
Get the complete information about CPU using the cpu_times() method:
>>> psutil.cpu_times()
Obtain single data, such as CPU time ratio of user user:
>>> psutil.cpu_times().user
Get the number of CPU:
>>> psutil.cpu_count() # The default logical=True , get the logical number
>>> psutil.cpu_count(logical=False) # To obtain CPU Physical number of
Memory information
Gets the total physical memory size and used memory:
>>> mem = psutil.virtual_memory()
>>> mem # Displays all the parameters
>>> mem.total # The total memory
>>> mem.used # Used memory
>>> mem.free # Gets the number of free memory
>>> psutil.swap_memory() # To obtain SWAP Partition information
Disk information
Get full disk information:
>>> psutil.disk_partitions()
Get partition usage:
>>> psutil.disk_usage('C:/') # The parameter is the disk partition you are on
Get the total number of IO of hard disk:
>>> psutil.disk_io_counters()
>>> psutil.disk_io_counters(perdisk=True) # Gets a single partition IO The number of
The network information
Obtain total IO information of the network:
>>> psutil.net_io_counters()
>>> psutil.net_io_counters(pernic=True) # Outputs a single network interface IO information
Other system information
Return the user information of the current login system:
>>> psutil.users()
Get boot time:
>>> psutil.cpu_times()
0
Process management
Process information
List all processes PID
>>> psutil.cpu_times()
1
Instantiate the process object
>>> psutil.cpu_times()
2
The use of the popen class
The popen class gets information about the application process that the user started.
>>> p = putil.Popen(["/usr/bin/python","-c","print('Hello')"],stdout=subprocess.PIPE)
>>> p.name()
>>> p.username() # The user who created the process
>>> p.communicate()
('hello\n',None)
>>> p.cpu_times() # Gets the process running CPU time