psutil是一个跨平台的Python库,用于获取系统信息和进程管理。以下是一些基本的用法:
- 获取CPU使用率
python
cpu_percent = psutil.cpu_percent(interval=1)
print(cpu_percent)
- 获取内存使用情况
python
memory_info = psutil.virtual_memory()
print(memory_info.percent)
- 获取磁盘使用情况
python
disk_usage = psutil.disk_usage('/')
print(disk_usage.percent)
- 获取所有进程ID
python
all_pids = psutil.pids()
print(all_pids)
- 获取指定进程信息
python
pid = 1234
process = psutil.Process(pid)
print(process.name())
print(process.status())
- 终止指定进程
python
pid = 1234
process = psutil.Process(pid)
process.terminate()
- 获取网络连接信息
python
import psutil
# 获取所有网络连接信息
connections = psutil.net_connections()
print(connections)
# 获取指定网络连接信息
connection = connections[0]
print(connection)
- 获取网络接口信息
python
import psutil
# 获取所有网络接口信息
interfaces = psutil.net_if_addrs()
print(interfaces)
# 获取指定网络接口信息
interface = interfaces['eth0']
print(interface)
- 获取网络流量信息
python
import psutil
# 获取当前进程的网络流量信息
process = psutil.Process()
net_io_counters = process.net_io_counters()
print(net_io_counters)
# 获取指定进程的网络流量信息
pid = 1234
process = psutil.Process(pid)
net_io_counters = process.net_io_counters()
print(net_io_counters)
- 获取网络连接状态信息
python
import psutil
# 获取所有网络连接状态信息
connections = psutil.net_connections()
for connection in connections:
print(connection.status)
# 获取指定网络连接状态信息
connection = connections[0]
print(connection.status)