psutil 是一个跨平台的库,用于在 Python 中检索系统运行时信息和操作。它可以用来监控系统资源的使用情况,如 CPU、内存、磁盘 I/O、网络等。以下是基于 psutil 开发一个简单监控工具的步骤:
步骤 1: 安装 psutil
首先,确保你的 Python 环境中已经安装了 psutil。如果没有安装,可以使用 pip 进行安装:
pip install psutil
步骤 2: 导入 psutil 模块
在你的 Python 脚本中导入 psutil 模块:
import psutil
步骤 3: 监控 CPU 使用情况
使用 psutil.cpu_percent() 函数来获取 CPU 的使用百分比。你可以指定一个间隔时间来定期检查:
import time
whileTrue: cpu_usage = psutil.cpu_percent(interval=1) print(f"CPU Usage: {cpu_usage}%") time.sleep(1) # 等待一秒再次检查
步骤 4: 监控内存使用情况
使用 psutil.virtual_memory() 来获取内存的统计信息:
mem = psutil.virtual_memory()print(f"Total Memory: {mem.total /(1024**3)} GB")print(f"Used Memory: {mem.used /(1024**3)} GB")print(f"Available Memory: {mem.available /(1024**3)} GB")
步骤 5: 监控磁盘 I/O
使用 psutil.disk_io_counters() 来获取磁盘的 I/O 统计信息:
disk_io = psutil.disk_io_counters()print(f"Disk Read: {disk_io.read_bytes /(1024**2)} MB")print(f"Disk Write: {disk_io.write_bytes /(1024**2)} MB")
步骤 6: 监控网络使用情况
使用 psutil.net_io_counters() 来获取网络的 I/O 统计信息:
net_io = psutil.net_io_counters()print(f"Bytes Sent: {net_io.bytes_sent /(1024**2)} MB")print(f"Bytes Received: {net_io.bytes_recv /(1024**2)} MB")
步骤 7: 监控进程信息
使用 psutil.process_iter() 来遍历系统中的所有进程,并获取特定进程的信息:
for proc in psutil.process_iter(['pid', 'name', 'cpu_percent']): print(f"PID: {proc.info['pid']}, Name: {proc.info['name']}, CPU: {proc.info['cpu_percent']}")
步骤 8: 整理输出和持久化数据
你可以将监控到的数据整理成表格或图表,甚至可以将数据持久化到文件或数据库中,以便后续分析:
import csv
withopen('monitoring_data.csv', 'w', newline='') asfile: writer = csv.writer(file) writer.writerow(['Timestamp', 'CPU Usage', 'Memory Usage', 'Disk Read', 'Disk Write', 'Bytes Sent', 'Bytes Received']) whileTrue: # 收集所有监控数据... # ... timestamp = psutil.sensors_time() writer.writerow([timestamp, cpu_usage, mem.used /(1024**3), disk_io.read_bytes /(1024**2), disk_io.write_bytes /(1024**2), net_io.bytes_sent /(1024**2), net_io.bytes_recv /(1024**2)]) time.sleep(5) # 每5秒写入一次数据
步骤 9: 运行监控工具
运行你的 Python 脚本,它将开始监控系统资源并输出或保存数据。你可以根据需要调整监控频率和数据收集的详细程度。
步骤 10: 可视化和分析
为了更好地理解监控数据,你可以使用数据可视化工具,如 Matplotlib 或 Seaborn,来创建图表和图形。此外,你还可以使用数据分析库,如 Pandas,来分析保存的数据。
完整的代码组织如下:
import psutilimport timeimport csvfrom datetime import datetime
# 定义监控的资源和采样间隔monitor_resources = { 'cpu': psutil.cpu_percent, 'memory': psutil.virtual_memory, 'disk_io': psutil.disk_io_counters, 'network_io': psutil.net_io_counters}
# 定义输出文件名output_file = 'monitoring_data.csv'
# 初始化CSV文件def init_csv_file(file_name): with open(file_name, 'w', newline='') as file: writer = csv.writer(file) writer.writerow(['Timestamp'] + list(monitor_resources.keys()))
# 监控资源并记录数据def monitor_resources_and_record(): init_csv_file(output_file) # 初始化CSV文件
while True: timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S') data_row = [timestamp]
for resource, func in monitor_resources.items(): value = func() data_row.append(value) print(f"{resource.capitalize()}: {value}")
with open(output_file, 'a', newline='') as file: writer = csv.writer(file) writer.writerow(data_row)
time.sleep(5) # 等待5秒再次检查
# 主函数if __name__ == '__main__': try: print("Starting system monitoring tool...") monitor_resources_and_record() # 开始监控资源并记录数据 except KeyboardInterrupt: print("Monitoring stopped by user.")
代码组织
导入模块:导入所需的库,包括psutil、time、csv和datetime。
定义监控资源:创建一个字典monitor_resources,包含要监控的资源类型和对应的psutil函数。
定义输出文件:设置输出CSV文件的名称。
初始化CSV文件:定义一个函数init_csv_file,用于创建CSV文件并写入标题行。
监控资源并记录数据:定义一个函数monitor_resources_and_record,用于定期监控资源并记录数据到CSV文件。
主函数:在__main__块中调用monitor_resources_and_record函数开始监控,并处理KeyboardInterrupt异常以便程序可以被用户中断。
实例运行
将上述代码保存到一个.py文件中。
运行该脚本。它将开始监控系统的资源使用情况,并每5秒将数据追加到monitoring_data.csv文件中。
你可以在控制台上看到实时输出的资源使用情况。
监控将持续进行,直到你手动中断它(例如,通过按下Ctrl+C)。
开源优测
领取专属 10元无门槛券
私享最新 技术干货