Python使用psutil获取系统性能信息
前言
psutil是Python上的一个用于获取系统运行的进程和资源利用率等信息的跨平台库,使用它可以很方便的在Python环境下获取系统信息从而进行相应操作。
安装
Linux
Ubuntu / Debian:
sudo apt-get install gcc python3-dev
pip3 install psutil
RedHat / CentOS:
sudo yum install gcc python3-devel
pip3 install psutil
If you’re on Python 2 use python-dev instead.
macOS
Install Xcode then run:
pip3 install psutil
Windows
Open a cmd.exe shell and run:
python3 -m pip install psutil
基础使用
CPU信息
-
psutil.cpu_times(percpu=False)
使用cpu_times 方法获取CPU完整信息,需要显示所有逻辑CPU信息,percpu = True可选。psutil.cpu_times().user可以获取用户user的CPU时间 -
psutil.cpu_percent(interval=None, percpu=False)
本机cpu的总占用率 -
psutil.cpu_times_percent(interval=None, percpu=False)
和cpu_percent()相近,但是返回的是百分比 -
psutil.cpu_count(logical=True)
获取CPU 的逻辑个数,默认logical=True。logical=False时获取CPU 的物理个数 -
psutil.cpu_stats()
返回如scpustats(ctx_switches=20455687, interrupts=6598984, soft_interrupts=2134212, syscalls=0)
的统计信息。 -
psutil.cpu_freq(percpu=False)
CPU 频率信息scpufreq(current=931.42925, min=800.0, max=3500.0)
-
psutil.getloadavg()
the average system load over the last 1, 5 and 15 minutes。
Memory信息
- psutil.virtual_memory()
获取内存完整信息,
mem = psutil.virtual_memory() ,
mem.total 获取内存总数
mem.free 获取空闲内存数
内存信息主要包括以下几个部分:
Total(内存总数)
Used(已使用的内存数)
Free(空闲内存数)
Buffers(缓冲使用数)
Cache(缓存使用数)
Swap(交换分区使用数)
- psutil.swap_memory()
获取swap分区信息
Disks信息
- psutil.disk_partitions(all=False)
获取磁盘完整信息 - psutil.disk_usage(path)
获取path所在分区(参数)使用情况 - psutil.disk_io_counters(perdisk=False, nowrap=True)
获取硬盘总的IO个数、读写信息。 'perdisk=True’参数获取单个分区IO个数、读写信息。
Network信息
- psutil.net_io_counters(pernic=False, nowrap=True)
获取网络总的IO信息,默认pernic=False。pernic=True输出每个网络接口的IO信息。 - psutil.net_connections(kind=‘inet’)
网路连接信息 - psutil.net_if_addrs()
网卡信息,网卡名、64位IP地址,32位IP地址、Mac地址。 - psutil.net_if_stats()
网卡状态
Sensors信息
- psutil.sensors_temperatures(fahrenheit=False)
温度信息 - psutil.sensors_fans()
风扇信息 - psutil.sensors_battery()
电池信息
其他信息
- psutil.boot_time()
返回当前登录系统的用户信息 - psutil.users()
获取开机时间,以Linux时间戳格式返回
高级使用
进程Processes信息统计
- psutil.pids()
- psutil.process_iter(attrs=None, ad_value=None)
- psutil.pid_exists(pid)
- psutil.wait_procs(procs, timeout=None, callback=None)
Exceptions
非常有用的Process class
classpsutil.Process(pid=None)
#统计PID为record_pid的进程cpu信息
p_pid = psutil.Process(record_pid)
cpu_percent = p_pid.cpu_percent(interval=1)#CPU占用比例
cpu_use_time = p_pid.cpu_times().user#CPU使用时间
#统计PID为record_pid的进程memory信息
p_pid = psutil.Process(record_pid)
rssmem = p_pid.memory_info().rss / NUM_EXPAND#以MB为单位
其中memory_info()详细信息如下:
更多细节移步官网参考相关文档,非常详尽。
参考资料
[1] psutil documentation
[2] psutil github
[3] python 获取系统资源使用信息
[4] Python系统性能信息模块
上一篇: Spring的循环依赖