Python 实时系统资源监控工具 - CPU、内存、GPU、网络使用率监测
import psutil
import GPUtil
import time
import sys
import keyboard
from termcolor import colored
def print_cpu_and_memory_usage():
""打印 CPU 和内存使用率""
cpu_percent = psutil.cpu_percent()
mem = psutil.virtual_memory()
mem_percent = mem.percent
mem_used = round(mem.used / 1024 / 1024, 2)
mem_total = round(mem.total / 1024 / 1024, 2)
print(colored(f' CPU 使用率: {cpu_percent}% ({psutil.cpu_count()} 核)', 'green'))
print(colored(f' 内存使用率: {mem_percent}% ({mem_used} / {mem_total} MB)', 'green'))
def print_gpu_usage():
""打印 GPU 使用率""
gpus = GPUtil.getGPUs()
for i, gpu in enumerate(gpus):
gpu_name = gpu.name
gpu_memory_total = gpu.memoryTotal
gpu_memory_used = gpu.memoryUsed
gpu_memory_free = gpu_memory_total - gpu_memory_used
gpu_memory_percent = gpu_memory_used / gpu_memory_total * 100
print(colored(f' GPU {i + 1} 型号: {gpu_name}', 'cyan'))
print(colored(f' 显存使用率: {gpu_memory_percent:.2f}% ({gpu_memory_used} / {gpu_memory_total} MB)', 'cyan'))
print(colored(f' 显存剩余大小: {gpu_memory_free:.2f} MB', 'cyan'))
def print_network_usage():
""打印网络使用率""
net_io = psutil.net_io_counters()
net_speed_sent = round(net_io.bytes_sent / 1024 / 1024, 2)
net_speed_recv = round(net_io.bytes_recv / 1024 / 1024, 2)
if 'en0' in psutil.net_if_stats():
print(colored(f' 有线网卡状态: {'已连接' if psutil.net_if_stats()['en0'].isup else '未连接'}', 'yellow'))
else:
print(colored(f' 有线网卡状态: 未连接', 'yellow'))
print(colored(f' 网卡上传速度: {net_speed_sent} MB/s', 'yellow'))
print(colored(f' 网卡下载速度: {net_speed_recv} MB/s', 'yellow'))
def print_instructions():
""打印程序操作说明""
print(colored('以下是程序操作说明:', 'magenta'))
print(' 1. 按 s 键刷新数据。')
print(' 2. 按 p 键暂停/继续程序输出。')
print(' 3. 按 c 键关闭程序。')
print(colored('--------------------------------------', 'magenta'))
def print_status(status, refresh_time):
""打印程序状态""
print(colored(f'当前监测状态:{status},上次刷新时间:{time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(refresh_time))}。', 'magenta'))
def refresh_data():
""刷新数据并返回状态和刷新时间""
refresh_time = time.time()
status = '已刷新'
print(colored('正在刷新数据,请稍候......', 'magenta'))
return status, refresh_time
def pause_resume(paused):
""暂停/继续程序输出""
if paused:
paused = False
status = '继续输出'
print(colored('已取消暂停,继续输出监测结果。', 'magenta'))
else:
paused = True
status = '已暂停'
print(colored('已暂停程序,停止输出监测结果。', 'magenta'))
return paused, status
def close_program():
""关闭程序""
status = '正在关闭'
refresh_time = time.time()
print(colored('正在关闭程序,请稍候......', 'magenta'))
sys.exit(0)
def main():
""主函数""
print_instructions()
print(colored('开始监测,按 Ctrl+C 可以结束程序。', 'magenta'))
paused = False
status = '运行中'
refresh_time = time.time()
while True:
if not paused:
print_cpu_and_memory_usage()
print_gpu_usage()
print_network_usage()
print_status(status, refresh_time)
if keyboard.is_pressed('s'): # s键
status, refresh_time = refresh_data()
time.sleep(1)
if keyboard.is_pressed('p'): # p键
paused, status = pause_resume(paused)
time.sleep(1)
if keyboard.is_pressed('c'): # c键
close_program()
time.sleep(1)
time.sleep(0.1)
if __name__ == '__main__':
main()
优化建议
- 使用多线程或多进程: 将监测部分放到独立的线程或进程中,避免阻塞主线程,提高用户体验。
- 使用
keyboard库的监听事件: 使用keyboard.on_press或keyboard.on_release监听键盘事件,代替keyboard.is_pressed,避免误触和漏触问题。 - 优化数据展示: 使用图表库(例如
matplotlib)绘制图表展示资源使用情况,方便用户理解趋势。 - 抽象监测方式: 将监测数据类型和方式抽象成类或函数,方便扩展和定制。
- 添加异常处理: 在代码中添加异常处理机制,防止程序崩溃。
代码解释
- 导入必要的库: 导入
psutil、GPUtil、time、sys、keyboard和termcolor库,用于获取系统信息、控制程序流程、处理键盘事件和显示彩色文字。 - 定义监测函数: 定义
print_cpu_and_memory_usage、print_gpu_usage、print_network_usage函数,分别用于获取并打印 CPU、内存、GPU 和网络使用情况。 - 定义辅助函数: 定义
print_instructions、print_status、refresh_data、pause_resume和close_program函数,用于显示操作说明、打印程序状态、刷新数据、暂停/继续程序输出以及关闭程序。 - 主函数: 在
main函数中,初始化程序状态,并使用循环不断监测系统资源,根据用户按键进行相应操作。 - 键盘事件处理: 使用
keyboard.is_pressed函数检测键盘事件,并根据按键执行相应的操作。
注意
- 确保安装了所有所需的库。
- 在使用该程序之前,请确认你已经了解了如何使用
psutil、GPUtil和keyboard库。 - 本代码仅供参考,你可以根据自己的需求进行修改和扩展。
原文地址: https://www.cveoy.top/t/topic/oxY3 著作权归作者所有。请勿转载和采集!