logo

Python实现系统性能监控:获取基础参数并写入文件全攻略

作者:carzy2025.09.25 23:04浏览量:0

简介:本文详细介绍如何使用Python获取系统基础性能参数(CPU、内存、磁盘、网络等),并通过代码示例演示将数据结构化写入文件,适用于系统监控、性能分析等场景。

Python实现系统性能监控:获取基础参数并写入文件全攻略

一、引言:系统性能监控的重要性

在IT运维、开发调试和性能优化场景中,实时获取系统基础性能参数是关键需求。无论是监控服务器运行状态、分析程序资源占用,还是构建自动化运维系统,都需要准确获取CPU使用率、内存消耗、磁盘I/O等核心指标。Python凭借其丰富的标准库和第三方工具,能够高效实现这一目标。本文将系统阐述如何使用Python获取系统性能参数,并将数据结构化写入文件,为开发者提供完整的解决方案。

二、核心性能参数解析与获取方法

1. CPU使用率获取

CPU是系统核心资源,其使用率直接反映计算负载。Python可通过psutil库获取:

  1. import psutil
  2. def get_cpu_info():
  3. # 获取CPU逻辑核心数
  4. cpu_count = psutil.cpu_count(logical=True)
  5. # 获取每个CPU核心的使用率(百分比)
  6. cpu_percent = psutil.cpu_percent(interval=1, percpu=True)
  7. # 获取全局CPU使用率
  8. total_cpu_percent = psutil.cpu_percent(interval=1)
  9. return {
  10. "cpu_cores": cpu_count,
  11. "per_cpu_percent": cpu_percent,
  12. "total_cpu_percent": total_cpu_percent
  13. }

关键点

  • interval=1参数确保采样间隔为1秒,提高数据准确性
  • percpu=True可获取每个逻辑核心的独立使用率
  • 适用于多核服务器监控场景

2. 内存信息获取

内存状态直接影响系统稳定性,需关注物理内存、交换分区等:

  1. def get_memory_info():
  2. mem = psutil.virtual_memory()
  3. swap = psutil.swap_memory()
  4. return {
  5. "total_memory": mem.total,
  6. "available_memory": mem.available,
  7. "used_memory": mem.used,
  8. "memory_percent": mem.percent,
  9. "swap_total": swap.total,
  10. "swap_used": swap.used,
  11. "swap_percent": swap.percent
  12. }

数据单位处理

  • 返回值为字节(bytes),建议转换为MB/GB:
    1. def bytes_to_gb(bytes_val):
    2. return round(bytes_val / (1024 ** 3), 2)

3. 磁盘信息获取

磁盘I/O和空间使用是关键监控项:

  1. def get_disk_info():
  2. partitions = psutil.disk_partitions()
  3. disk_usage = []
  4. for partition in partitions:
  5. usage = psutil.disk_usage(partition.mountpoint)
  6. disk_usage.append({
  7. "device": partition.device,
  8. "mountpoint": partition.mountpoint,
  9. "total": usage.total,
  10. "used": usage.used,
  11. "free": usage.free,
  12. "percent": usage.percent
  13. })
  14. # 获取磁盘IO统计(读写速度)
  15. io_counters = psutil.disk_io_counters()
  16. return {
  17. "partitions": disk_usage,
  18. "io_read_bytes": io_counters.read_bytes,
  19. "io_write_bytes": io_counters.write_bytes
  20. }

4. 网络信息获取

网络带宽和连接状态监控:

  1. def get_network_info():
  2. # 获取网络接口信息
  3. net_io = psutil.net_io_counters()
  4. # 获取活动连接数
  5. connections = psutil.net_connections(kind='inet')
  6. return {
  7. "bytes_sent": net_io.bytes_sent,
  8. "bytes_recv": net_io.bytes_recv,
  9. "active_connections": len(connections)
  10. }

三、数据结构化与文件写入实现

1. JSON格式写入

推荐使用JSON格式存储性能数据,便于后续解析:

  1. import json
  2. from datetime import datetime
  3. def write_to_json(data, filename="system_performance.json"):
  4. timestamp = datetime.now().isoformat()
  5. structured_data = {
  6. "timestamp": timestamp,
  7. "performance_data": data
  8. }
  9. with open(filename, 'a') as f: # 追加模式
  10. json.dump(structured_data, f, indent=4)
  11. f.write("\n") # 每个记录换行

2. CSV格式写入

适合表格化分析的场景:

  1. import csv
  2. def write_to_csv(data, filename="system_performance.csv"):
  3. fieldnames = [
  4. "timestamp", "cpu_percent", "memory_percent",
  5. "disk_used_percent", "bytes_sent", "bytes_recv"
  6. ]
  7. # 准备单行数据(示例简化)
  8. row = {
  9. "timestamp": datetime.now().isoformat(),
  10. "cpu_percent": data["total_cpu_percent"],
  11. "memory_percent": data["memory_percent"],
  12. "disk_used_percent": data["partitions"][0]["percent"],
  13. "bytes_sent": data["bytes_sent"],
  14. "bytes_recv": data["bytes_recv"]
  15. }
  16. # 写入模式处理
  17. write_mode = 'a' if os.path.exists(filename) else 'w'
  18. with open(filename, write_mode, newline='') as f:
  19. writer = csv.DictWriter(f, fieldnames=fieldnames)
  20. if write_mode == 'w':
  21. writer.writeheader()
  22. writer.writerow(row)

3. 数据库存储方案(扩展)

对于长期监控,建议接入SQLite等轻量级数据库:

  1. import sqlite3
  2. def init_db(db_name="performance.db"):
  3. conn = sqlite3.connect(db_name)
  4. c = conn.cursor()
  5. c.execute('''CREATE TABLE IF NOT EXISTS performance
  6. (timestamp TEXT, cpu REAL, memory REAL, disk REAL,
  7. net_sent REAL, net_recv REAL)''')
  8. conn.commit()
  9. conn.close()
  10. def write_to_db(data, db_name="performance.db"):
  11. conn = sqlite3.connect(db_name)
  12. c = conn.cursor()
  13. c.execute("INSERT INTO performance VALUES (?,?,?,?,?,?)", (
  14. datetime.now().isoformat(),
  15. data["total_cpu_percent"],
  16. data["memory_percent"],
  17. data["partitions"][0]["percent"],
  18. data["bytes_sent"],
  19. data["bytes_recv"]
  20. ))
  21. conn.commit()
  22. conn.close()

四、完整实现示例

  1. import psutil
  2. import json
  3. from datetime import datetime
  4. import os
  5. def collect_system_metrics():
  6. return {
  7. "cpu": get_cpu_info(),
  8. "memory": get_memory_info(),
  9. "disk": get_disk_info(),
  10. "network": get_network_info()
  11. }
  12. def main():
  13. # 初始化数据库(可选)
  14. init_db()
  15. while True: # 示例循环,实际应考虑退出条件
  16. metrics = collect_system_metrics()
  17. # 写入JSON文件
  18. write_to_json(metrics)
  19. # 写入CSV(简化版)
  20. simplified_data = {
  21. "total_cpu_percent": metrics["cpu"]["total_cpu_percent"],
  22. "memory_percent": metrics["memory"]["memory_percent"],
  23. "disk_percent": metrics["disk"]["partitions"][0]["percent"],
  24. "bytes_sent": metrics["network"]["bytes_sent"],
  25. "bytes_recv": metrics["network"]["bytes_recv"]
  26. }
  27. write_to_csv(simplified_data)
  28. # 写入数据库
  29. write_to_db(simplified_data)
  30. print(f"Metrics collected at {datetime.now()}")
  31. if __name__ == "__main__":
  32. main()

五、最佳实践与优化建议

  1. 采样频率控制

    • 生产环境建议每5-60秒采样一次
    • 使用time.sleep()控制循环间隔
  2. 异常处理机制

    1. try:
    2. metrics = collect_system_metrics()
    3. except Exception as e:
    4. print(f"Error collecting metrics: {e}")
    5. # 可添加邮件/短信告警
  3. 文件轮转策略

    • 按日期分割文件(如performance_2023-08-01.json
    • 设置文件大小限制(超过100MB创建新文件)
  4. 性能影响评估

    • psutil本身消耗极低(<1% CPU)
    • 避免在高负载系统上设置过高采样频率

六、进阶应用场景

  1. 可视化看板

    • 使用Python的matplotlibplotly生成趋势图
    • 结合Grafana等工具构建专业监控面板
  2. 异常检测

    • 设置阈值告警(如CPU持续>90%触发通知)
    • 实现基于历史数据的智能预测
  3. 容器化部署

    • 将监控脚本打包为Docker容器
    • 使用Kubernetes的CronJob定期执行

七、总结与展望

本文系统介绍了Python获取系统性能参数的核心方法,通过psutil库实现了CPU、内存、磁盘、网络等关键指标的采集,并提供了JSON、CSV、数据库三种存储方案。实际部署时,建议:

  1. 根据监控需求选择合适的数据存储方式
  2. 结合定时任务实现自动化采集
  3. 添加异常处理和告警机制
  4. 定期分析历史数据优化系统配置

未来可扩展方向包括:支持更多操作系统(如Windows/Linux差异处理)、集成Prometheus等监控生态、开发Web界面实时查看数据等。通过完善的性能监控体系,能够显著提升系统稳定性和运维效率。

相关文章推荐

发表评论