introduce
psutil can easily achieve the process of system operation and system utilization.
Import module
import psutils
Obtaining system performance information
CPU Info
Use the cpu_times() method to get the complete information of the CPU:
>>> psutil.cpu_times()
Get individual data, such as CPU time ratio of user user:
>>> psutil.cpu_times().user
Get the number of CPU s:
>>> psutil.cpu_count() # Default logic = True to get the number of logics >>> psutil.cpu_count(logical=False) # Get the physical number of CPU s
Memory information
Get the total physical memory size and used memory:
>>> mem = psutil.virtual_memory() >>> mem # Display all parameters >>> mem.total # Total memory >>> mem.used # Used memory >>> mem.free # Get the number of free memory >>> psutil.swap_memory() # Get SWAP partition information
Disk information
Get complete disk information:
>>> psutil.disk_partitions()
Get partition usage:
>>> psutil.disk_usage('C:/') # The internal parameters are the partitions of the disks in which they are located.
Get the total IO number of hard disks:
>>> psutil.disk_io_counters() >>> psutil.disk_io_counters(perdisk=True) # Get the number of IO s for a single partition
network information
Get the total IO information of the network:
>>> psutil.net_io_counters() >>> psutil.net_io_counters(pernic=True) # Output IO information for a single network interface
Other system information
Returns user information for the current login system:
>>> psutil.users()
Get boot time:
>>> psutil.boot_time() # Returns in Linux timestamp format # If you want to convert to natural time format: >>> datetime.datetime.fromtimestamp(psutil.boot_time()).strftime("%Y-%m-%d %H:%M:%S")
Process management
Process information
List all process PID s
>>> psutil.pids()
Instantiate process objects
>>> p = psutil.Process(716) >>> p.name() # Process name >>> p.exe() # Process bin path >>> p.cwd() # Absolute path of process working directory >>> p.status() # Process state >>> p.create_time() # Process creation time >>> p.uids() # Process uid information >>> p.gids() # Process gid information >>> p.cpu_times() # Process CPU time information >>> p.cpu_affinity() # Affinity of get process >>> p.memory_percent() # Process memory utilization >>> p.num_threads() # Number of threads opened by a process
Use of popen class
The popen class can obtain information about the application process initiated by the user.
>>> p = putil.Popen(["/usr/bin/python","-c","print('Hello')"],stdout=subprocess.PIPE) >>> p.name() >>> p.username() # Users who create processes >>> p.communicate() ('hello\n',None) >>> p.cpu_times() # Get CPU time for the process to run