第二天 流程控制(if/for/while) - 列表/元组/字典操作
前言
在IT运维和系统管理领域,资源监控是至关重要的基础技能。本教程将带领Python初学者,通过编写一个实用的系统资源监控脚本,掌握Python基础语法中的流程控制、数据结构操作等核心知识。即使您完全没有编程经验,只要跟着本文一步步实践,也能在2小时内完成第一个Python实战项目!
一、Python基础快速入门
1.1 流程控制语句
流程控制是编程中的决策系统,掌握它们就能让程序具备"思考能力"。
1.1.1 if条件判断
# 监控CPU使用率告警示例
cpu_usage = 85
if cpu_usage > 90:
print("警告:CPU使用率过高!")
elif cpu_usage > 80:
print("注意:CPU使用率偏高")
else:
print("CPU使用率正常")
1.1.2 for循环
# 模拟监控数据采集(5次采样)
for i in range(1, 6):
print(f"正在进行第 {i} 次资源采集...")
# 这里可以添加实际的采集代码
1.1.3 while循环
# 持续监控直到手动停止
import time
monitor = True
while monitor:
print("正在监控系统资源...")
time.sleep(5) # 每5秒采集一次
1.2 核心数据结构操作
1.2.1 列表(List)—— 监控数据存储利器
# 创建存储CPU使用率的列表
cpu_history = []
# 添加监控数据
for _ in range(5):
cpu_history.append(psutil.cpu_percent())
# 分析数据
print("平均CPU使用率:", sum(cpu_history)/len(cpu_history))
1.2.2 元组(Tuple)—— 不可变数据集
# 定义监控阈值常量
THRESHOLDS = (90, 80, 70) # (危险值, 警告值, 注意值)
# 访问元素
print("内存危险阈值:", THRESHOLDS[0])
1.2.3 字典(Dict)—— 结构化监控数据
# 创建监控数据字典
system_status = {
"cpu": {
"usage": 35.6,
"temp": 45
},
"memory": {
"total": 16,
"used": 12.3
}
}
# 更新数据
system_status["cpu"]["usage"] = psutil.cpu_percent()
# 遍历字典
for category, metrics in system_status.items():
print(f"{category}监控指标:")
for k, v in metrics.items():
print(f" {k}: {v}")
二、实战:系统资源监控脚本开发
2.1 环境准备
安装所需库:
pip install psutil # 跨平台系统监控库
2.2 基础版本实现
步骤1:获取系统信息
import psutil
import time
def get_system_info():
"""获取系统资源信息"""
return {
"timestamp": time.strftime("%Y-%m-%d %H:%M:%S"),
"cpu_usage": psutil.cpu_percent(interval=1),
"memory_usage": psutil.virtual_memory().percent,
"disk_usage": psutil.disk_usage("/").percent,
"network_io": psutil.net_io_counters()
}
步骤2:数据处理模块
def process_data(data, history):
"""处理并存储监控数据"""
# 添加最新数据到历史记录(限制保留最近10条)
history.append(data)
if len(history) > 10:
history.pop(0)
# 生成统计信息
stats = {
"max_cpu": max([d["cpu_usage"] for d in history]),
"avg_memory": sum([d["memory_usage"] for d in history])/len(history)
}
return stats
步骤3:监控报警逻辑
def check_alert(data):
"""资源使用报警检查"""
alerts = []
if data["cpu_usage"] > 90:
alerts.append("CPU使用超过90%!")
if data["memory_usage"] > 85:
alerts.append("内存使用超过85%!")
return alerts
2.3 完整脚本集成
import psutil
import time
from collections import deque
class SystemMonitor:
def __init__(self):
self.history = deque(maxlen=60) # 保存最近60次记录
self.alert_count = 0
def start_monitoring(self, interval=5):
"""启动监控"""
try:
while True:
# 采集数据
data = self.collect_data()
# 处理数据
stats = self.process_data(data)
# 检查报警
alerts = self.check_alerts(data)
# 显示信息
self.display_status(data, stats, alerts)
time.sleep(interval)
except KeyboardInterrupt:
print("\n监控已停止")
def collect_data(self):
"""收集系统数据"""
return {
"timestamp": time.strftime("%Y-%m-%d %H:%M:%S"),
"cpu_usage": psutil.cpu_percent(interval=1),
"memory_usage": psutil.virtual_memory().percent,
"disk_usage": psutil.disk_usage("/").percent,
"network_sent": psutil.net_io_counters().bytes_sent,
"network_recv": psutil.net_io_counters().bytes_recv
}
def process_data(self, data):
"""处理监控数据"""
self.history.append(data)
# 计算统计指标
return {
"avg_cpu": sum(d["cpu_usage"] for d in self.history)/len(self.history),
"max_memory": max(d["memory_usage"] for d in self.history),
"disk_trend": self.history[-1]["disk_usage"] - self.history[0]["disk_usage"]
}
def check_alerts(self, data):
"""检查系统警报"""
alerts = []
if data["cpu_usage"] > 90:
alerts.append("CPU使用超过90%!")
if data["memory_usage"] > 85:
alerts.append("内存使用超过85%!")
if data["disk_usage"] > 95:
alerts.append("磁盘使用超过95%!")
return alerts
def display_status(self, data, stats, alerts):
"""显示监控信息"""
print("\n" + "="*40)
print(f"系统状态报告 ({data['timestamp']})")
print("-"*40)
print(f"CPU使用率: {data['cpu_usage']}% (平均: {stats['avg_cpu']:.1f}%)")
print(f"内存使用率: {data['memory_usage']}% (最高: {stats['max_memory']}%)")
print(f"磁盘使用率: {data['disk_usage']}% (趋势: {stats['disk_trend']:+}%)")
print(f"网络流量: 发送 {data['network_sent']//1024}KB / 接收 {data['network_recv']//1024}KB")
if alerts:
print("\n!! 警报 !!")
for alert in alerts:
print(f"• {alert}")
self.alert_count += 1
if __name__ == "__main__":
monitor = SystemMonitor()
monitor.start_monitoring()
三、脚本功能扩展建议
- 数据持久化:使用CSV模块保存监控记录
import csv
def save_to_csv(data):
with open("system_log.csv", "a") as f:
writer = csv.writer(f)
writer.writerow([
data["timestamp"],
data["cpu_usage"],
data["memory_usage"],
data["disk_usage"]
])
- 可视化展示:使用Matplotlib生成图表
import matplotlib.pyplot as plt
def plot_cpu_usage(history):
timestamps = [d["timestamp"] for d in history]
cpu_values = [d["cpu_usage"] for d in history]
plt.plot(timestamps, cpu_values)
plt.title("CPU使用率趋势图")
plt.xticks(rotation=45)
plt.show()
- 邮件报警功能:使用smtplib发送报警邮件
import smtplib
from email.mime.text import MIMEText
def send_alert_email(message):
msg = MIMEText(message)
msg["Subject"] = "系统资源警报"
msg["From"] = "monitor@example.com"
msg["To"] = "admin@example.com"
with smtplib.SMTP("smtp.example.com") as server:
server.send_message(msg)
四、学习路线建议
-
巩固基础:
- 多练习列表推导式等Python特性
- 掌握with语句处理文件操作
- 学习使用datetime模块处理时间
-
项目扩展:
- 添加Web界面展示监控数据(Flask/Django)
- 实现多服务器监控功能
- 开发自动化清理磁盘脚本
-
深入学习:
- 了解多线程/异步编程提升脚本效率
- 学习使用Pandas进行数据分析
- 探索Docker容器监控方案
五、总结
通过本教程,我们完成了:
✅ 掌握Python流程控制语句
✅ 熟练操作列表、元组、字典
✅ 开发完整的系统监控脚本
✅ 学习数据处理和异常处理技巧
这个项目不仅巩固了Python基础知识,更展示了如何将编程技能应用到实际工作中。建议读者尝试扩展脚本功能,例如添加可视化图表或短信报警功能,这将大大提升项目的实用价值。
学习资源推荐:
- 官方psutil文档:https://psutil.readthedocs.io/
- Python标准库教程:https://docs.python.org/3/library/
- 自动化运维实战案例:https://github.com/geekcomputers/Python
欢迎在评论区分享你的改进版本!下期我们将探讨如何为这个监控脚本添加Web可视化界面,敬请期待!