Python实现系统性能监控:获取基础参数并写入文件全攻略
2025.09.25 23:04浏览量:0简介:本文详细介绍如何使用Python获取系统基础性能参数(CPU、内存、磁盘、网络等),并通过代码示例演示将数据结构化写入文件,适用于系统监控、性能分析等场景。
Python实现系统性能监控:获取基础参数并写入文件全攻略
一、引言:系统性能监控的重要性
在IT运维、开发调试和性能优化场景中,实时获取系统基础性能参数是关键需求。无论是监控服务器运行状态、分析程序资源占用,还是构建自动化运维系统,都需要准确获取CPU使用率、内存消耗、磁盘I/O等核心指标。Python凭借其丰富的标准库和第三方工具,能够高效实现这一目标。本文将系统阐述如何使用Python获取系统性能参数,并将数据结构化写入文件,为开发者提供完整的解决方案。
二、核心性能参数解析与获取方法
1. CPU使用率获取
CPU是系统核心资源,其使用率直接反映计算负载。Python可通过psutil库获取:
import psutildef get_cpu_info():# 获取CPU逻辑核心数cpu_count = psutil.cpu_count(logical=True)# 获取每个CPU核心的使用率(百分比)cpu_percent = psutil.cpu_percent(interval=1, percpu=True)# 获取全局CPU使用率total_cpu_percent = psutil.cpu_percent(interval=1)return {"cpu_cores": cpu_count,"per_cpu_percent": cpu_percent,"total_cpu_percent": total_cpu_percent}
关键点:
interval=1参数确保采样间隔为1秒,提高数据准确性percpu=True可获取每个逻辑核心的独立使用率- 适用于多核服务器监控场景
2. 内存信息获取
内存状态直接影响系统稳定性,需关注物理内存、交换分区等:
def get_memory_info():mem = psutil.virtual_memory()swap = psutil.swap_memory()return {"total_memory": mem.total,"available_memory": mem.available,"used_memory": mem.used,"memory_percent": mem.percent,"swap_total": swap.total,"swap_used": swap.used,"swap_percent": swap.percent}
数据单位处理:
- 返回值为字节(bytes),建议转换为MB/GB:
def bytes_to_gb(bytes_val):return round(bytes_val / (1024 ** 3), 2)
3. 磁盘信息获取
磁盘I/O和空间使用是关键监控项:
def get_disk_info():partitions = psutil.disk_partitions()disk_usage = []for partition in partitions:usage = psutil.disk_usage(partition.mountpoint)disk_usage.append({"device": partition.device,"mountpoint": partition.mountpoint,"total": usage.total,"used": usage.used,"free": usage.free,"percent": usage.percent})# 获取磁盘IO统计(读写速度)io_counters = psutil.disk_io_counters()return {"partitions": disk_usage,"io_read_bytes": io_counters.read_bytes,"io_write_bytes": io_counters.write_bytes}
4. 网络信息获取
网络带宽和连接状态监控:
def get_network_info():# 获取网络接口信息net_io = psutil.net_io_counters()# 获取活动连接数connections = psutil.net_connections(kind='inet')return {"bytes_sent": net_io.bytes_sent,"bytes_recv": net_io.bytes_recv,"active_connections": len(connections)}
三、数据结构化与文件写入实现
1. JSON格式写入
推荐使用JSON格式存储性能数据,便于后续解析:
import jsonfrom datetime import datetimedef write_to_json(data, filename="system_performance.json"):timestamp = datetime.now().isoformat()structured_data = {"timestamp": timestamp,"performance_data": data}with open(filename, 'a') as f: # 追加模式json.dump(structured_data, f, indent=4)f.write("\n") # 每个记录换行
2. CSV格式写入
适合表格化分析的场景:
import csvdef write_to_csv(data, filename="system_performance.csv"):fieldnames = ["timestamp", "cpu_percent", "memory_percent","disk_used_percent", "bytes_sent", "bytes_recv"]# 准备单行数据(示例简化)row = {"timestamp": datetime.now().isoformat(),"cpu_percent": data["total_cpu_percent"],"memory_percent": data["memory_percent"],"disk_used_percent": data["partitions"][0]["percent"],"bytes_sent": data["bytes_sent"],"bytes_recv": data["bytes_recv"]}# 写入模式处理write_mode = 'a' if os.path.exists(filename) else 'w'with open(filename, write_mode, newline='') as f:writer = csv.DictWriter(f, fieldnames=fieldnames)if write_mode == 'w':writer.writeheader()writer.writerow(row)
3. 数据库存储方案(扩展)
对于长期监控,建议接入SQLite等轻量级数据库:
import sqlite3def init_db(db_name="performance.db"):conn = sqlite3.connect(db_name)c = conn.cursor()c.execute('''CREATE TABLE IF NOT EXISTS performance(timestamp TEXT, cpu REAL, memory REAL, disk REAL,net_sent REAL, net_recv REAL)''')conn.commit()conn.close()def write_to_db(data, db_name="performance.db"):conn = sqlite3.connect(db_name)c = conn.cursor()c.execute("INSERT INTO performance VALUES (?,?,?,?,?,?)", (datetime.now().isoformat(),data["total_cpu_percent"],data["memory_percent"],data["partitions"][0]["percent"],data["bytes_sent"],data["bytes_recv"]))conn.commit()conn.close()
四、完整实现示例
import psutilimport jsonfrom datetime import datetimeimport osdef collect_system_metrics():return {"cpu": get_cpu_info(),"memory": get_memory_info(),"disk": get_disk_info(),"network": get_network_info()}def main():# 初始化数据库(可选)init_db()while True: # 示例循环,实际应考虑退出条件metrics = collect_system_metrics()# 写入JSON文件write_to_json(metrics)# 写入CSV(简化版)simplified_data = {"total_cpu_percent": metrics["cpu"]["total_cpu_percent"],"memory_percent": metrics["memory"]["memory_percent"],"disk_percent": metrics["disk"]["partitions"][0]["percent"],"bytes_sent": metrics["network"]["bytes_sent"],"bytes_recv": metrics["network"]["bytes_recv"]}write_to_csv(simplified_data)# 写入数据库write_to_db(simplified_data)print(f"Metrics collected at {datetime.now()}")if __name__ == "__main__":main()
五、最佳实践与优化建议
采样频率控制:
- 生产环境建议每5-60秒采样一次
- 使用
time.sleep()控制循环间隔
异常处理机制:
try:metrics = collect_system_metrics()except Exception as e:print(f"Error collecting metrics: {e}")# 可添加邮件/短信告警
文件轮转策略:
- 按日期分割文件(如
performance_2023-08-01.json) - 设置文件大小限制(超过100MB创建新文件)
- 按日期分割文件(如
性能影响评估:
psutil本身消耗极低(<1% CPU)- 避免在高负载系统上设置过高采样频率
六、进阶应用场景
可视化看板:
- 使用Python的
matplotlib或plotly生成趋势图 - 结合Grafana等工具构建专业监控面板
- 使用Python的
异常检测:
- 设置阈值告警(如CPU持续>90%触发通知)
- 实现基于历史数据的智能预测
容器化部署:
- 将监控脚本打包为Docker容器
- 使用Kubernetes的CronJob定期执行
七、总结与展望
本文系统介绍了Python获取系统性能参数的核心方法,通过psutil库实现了CPU、内存、磁盘、网络等关键指标的采集,并提供了JSON、CSV、数据库三种存储方案。实际部署时,建议:
- 根据监控需求选择合适的数据存储方式
- 结合定时任务实现自动化采集
- 添加异常处理和告警机制
- 定期分析历史数据优化系统配置
未来可扩展方向包括:支持更多操作系统(如Windows/Linux差异处理)、集成Prometheus等监控生态、开发Web界面实时查看数据等。通过完善的性能监控体系,能够显著提升系统稳定性和运维效率。

发表评论
登录后可评论,请前往 登录 或 注册