文章目录
一、背景
在Python的世界里,有一些库因其强大的功能和易用性而备受开发者们的喜爱。今天,我们要介绍的就是其中的一员——psutil库。psutil(python system and process utilities)是一个跨平台的第三方库,用于获取系统运行时的进程和系统利用率(包括CPU、内存、磁盘、网络等)信息。它主要用于系统监控,性能分析,进程管理等场景。
二、安装&基本使用
psutil安装:
pip install psutil
安装完成后,我们就可以开始使用psutil库了。下面,我们将介绍一些常用的功能。
1、获取CPU信息
psutil库可以获取CPU的使用情况。例如,我们可以使用psutil.cpu_percent(interval=1)来获取CPU的使用率。
import psutil
cpu_percent = psutil.cpu_percent(interval=1)
print(f'CPU usage: {
cpu_percent}%')
2、获取内存信息
我们可以使用psutil.virtual_memory()来获取系统的内存使用情况。
import psutil
mem_info = psutil.virtual_memory()
print(f'Total memory: {
mem_info.total / (1024**3):.2f} GB')
print(f'Used memory: {
mem_info.used / (1024**3):.2f} GB')
print(f'Memory usage: {
mem_info.percent}%')
3、获取磁盘信息
psutil库也可以获取磁盘的使用情况。例如,我们可以使用psutil.disk_usage(‘/’)来获取根目录的磁盘使用情况。
import psutil
disk_usage = psutil.disk_usage('/')
print(f'Total disk space: {
disk_usage.total / (1024**3):.2f} GB')
print(f'Used disk space: