This article brings you an introduction (detailed) about the use of the psutil library in Python. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
Introduction
psutil can easily obtain the processes running on the system and system utilization.
Import module
import psutils
Get system performance information
CPU information
Use cpu_times() method Get complete information about the CPU:
>>> psutil.cpu_times()
Get individual data, such as user user’s CPU time ratio:
>>> psutil.cpu_times().user
Get the number of CPUs:
>>> psutil.cpu_count() # 默认logical=True,获取逻辑个数 >>> psutil.cpu_count(logical=False) # 获取CPU的物理个数
Memory information
Get the total physical memory size and used memory:
>>> mem = psutil.virtual_memory() >>> mem # 显示所有的参数 >>> mem.total # 总内存 >>> mem.used # 已使用内存 >>> mem.free # 获取空闲内存数 >>> psutil.swap_memory() # 获取SWAP分区信息
Disk information
Get the complete disk information:
>>> psutil.disk_partitions()
Get the partition usage:
>>> psutil.disk_usage('C:/') # 里面参数为所在磁盘分区
Get the total IO number of the hard disk:
>>> psutil.disk_io_counters() >>> psutil.disk_io_counters(perdisk=True) # 获取单个分区的IO个数
Network information
Get the total network IO information :
>>> psutil.net_io_counters() >>> psutil.net_io_counters(pernic=True) # 输出单个网络接口的IO信息
Other system information
Return the user information currently logged into the system:
>>> psutil.users()
Get the boot time:
>>> psutil.boot_time() # 以Linux时间戳格式返回 # 如果想要转换成自然时间格式: >>> datetime.datetime.fromtimestamp(psutil.boot_time()).strftime("%Y-%m-%d %H:%M:%S")
Process Management
Process Information
List all process PIDs
>>> psutil.pids()
Instantiate process objects
>>> p = psutil.Process(716) >>> p.name() # 进程名 >>> p.exe() # 进程bin路径 >>> p.cwd() # 进程工作目录的绝对路径 >>> p.status() # 进程状态 >>> p.create_time() # 进程创建时间 >>> p.uids() # 进程uid信息 >>> p.gids() # 进程gid信息 >>> p.cpu_times() # 进程CPU时间信息 >>> p.cpu_affinity() # get进程的亲和度 >>> p.memory_percent() # 进程内存使用率 >>> p.num_threads() # 进程开启的线程数
Usage of popen class
The popen class can obtain user-initiated application process information.
>>> p = putil.Popen(["/usr/bin/python","-c","print('Hello')"],stdout=subprocess.PIPE) >>> p.name() >>> p.username() # 创建进程的用户 >>> p.communicate() ('hello\n',None) >>> p.cpu_times() # 得到进程运行的CPU时间
The above is the detailed content of Introduction to the use of psutil library in Python (detailed). For more information, please follow other related articles on the PHP Chinese website!