【python学习】基础篇-常用第三方库-psutil:用于获取CPU、磁盘与网络等系统信息和进程管理

psutil是一个跨平台的Python库,用于获取系统信息和进程管理。以下是一些基本的用法:

  1. 获取CPU使用率
python 复制代码
cpu_percent = psutil.cpu_percent(interval=1)
print(cpu_percent)
  1. 获取内存使用情况
python 复制代码
memory_info = psutil.virtual_memory()
print(memory_info.percent)
  1. 获取磁盘使用情况
python 复制代码
disk_usage = psutil.disk_usage('/')
print(disk_usage.percent)
  1. 获取所有进程ID
python 复制代码
all_pids = psutil.pids()
print(all_pids)
  1. 获取指定进程信息
python 复制代码
pid = 1234
process = psutil.Process(pid)
print(process.name())
print(process.status())
  1. 终止指定进程
python 复制代码
pid = 1234
process = psutil.Process(pid)
process.terminate()
  1. 获取网络连接信息
python 复制代码
import psutil

# 获取所有网络连接信息
connections = psutil.net_connections()
print(connections)

# 获取指定网络连接信息
connection = connections[0]
print(connection)
  1. 获取网络接口信息
python 复制代码
import psutil

# 获取所有网络接口信息
interfaces = psutil.net_if_addrs()
print(interfaces)

# 获取指定网络接口信息
interface = interfaces['eth0']
print(interface)
  1. 获取网络流量信息
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)
  1. 获取网络连接状态信息
python 复制代码
import psutil

# 获取所有网络连接状态信息
connections = psutil.net_connections()
for connection in connections:
    print(connection.status)

# 获取指定网络连接状态信息
connection = connections[0]
print(connection.status)
相关推荐
m4Rk_6 小时前
【论文阅读】Agent 记忆机制(83):Inside Out——用可演化 PersonaTree 构建 Agent 的核心长期记忆
论文阅读·人工智能·学习·开源·github
Johny_Zhao6 小时前
FreeRADIUS + 华为AC/AP + 802.1X/WPA2-Enterprise 无线认证对接部署完整指南
网络·网络安全·信息安全·ldap·radius·huawei·系统运维·centos8
杨杨杨大侠6 小时前
Jev、Kev、Laya:决策模型怎么选,什么时候需要微调?
人工智能·python·agent
LOVE️YOU6 小时前
Python 在定义函数时,究竟定义的是什么?
python
段一凡-华北理工大学6 小时前
大模型应用开发 100 天:Python + LLM 从入门到精通 day26~Prompt 调试与优化——A/B 测试与效果评估
windows·python·大模型·prompt·智能体·提示词工程·高炉智能化
Minecraft红客6 小时前
以撒的结合
python·游戏·电脑·娱乐
鬓戈7 小时前
Rust 语言与 AI 应用生态调研及学习路径
人工智能·学习·rust
天远API7 小时前
零信任架构实战:基于天远人企关联构建自动化图谱网关
网络·人工智能·架构·自动化
传奇开心果编程7 小时前
【SwiftUI娓娓道来】第3课:让界面活起来——交互与动画指南
学习·macos·ui·ios·swiftui·swift
Circ.7 小时前
Python 调试 Litellm 本地大模型接口:模型列表与对话接口实操踩坑记录
开发语言·python