温馨提示×

CentOS Python资源如何监控

小樊
36
2025-11-10 04:31:27
栏目: 编程语言

1. 使用psutil库监控系统资源
psutil是跨平台的Python库,可实时获取CPU、内存、磁盘、网络等系统资源使用情况,适用于CentOS环境下监控Python进程及周边资源。示例代码:

import psutil

# 获取CPU使用率(间隔1秒)
cpu_percent = psutil.cpu_percent(interval=1)
print(f"CPU使用率: {cpu_percent}%")

# 获取内存信息(总内存、已用、可用、使用率)
memory = psutil.virtual_memory()
print(f"总内存: {memory.total / (1024**3):.2f}GB, 已用: {memory.used / (1024**3):.2f}GB, 使用率: {memory.percent}%")

# 获取磁盘使用情况(根分区)
disk = psutil.disk_usage('/')
print(f"磁盘总空间: {disk.total / (1024**3):.2f}GB, 已用: {disk.used / (1024**3):.2f}GB, 使用率: {disk.percent}%")

# 获取网络IO(发送/接收字节数)
net_io = psutil.net_io_counters()
print(f"发送字节数: {net_io.bytes_sent / (1024**2):.2f}MB, 接收字节数: {net_io.bytes_recv / (1024**2):.2f}MB")

通过循环调用上述函数,可实现定时监控;结合matplotlib库还能绘制资源使用趋势图。

2. 构建Web监控面板(Flask+psutil)
使用Flask框架将监控数据可视化,通过Web界面实时查看。示例步骤:

  • 安装依赖:pip install flask psutil
  • 创建Flask应用(app.py):
from flask import Flask, jsonify, render_template
import psutil

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html')  # 创建templates/index.html展示数据

@app.route('/api/resource')
def resource():
    cpu = psutil.cpu_percent(interval=1)
    memory = psutil.virtual_memory().percent
    return jsonify({"cpu": cpu, "memory": memory})

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)
  • 创建HTML模板(templates/index.html):
<!DOCTYPE html>
<html>
<body>
    <h2>CPU使用率: <span id="cpu">-</span>%</h2>
    <h2>内存使用率: <span id="memory">-</span>%</h2>
    <script>
        setInterval(async () => {
            const res = await fetch('/api/resource');
            const data = await res.json();
            document.getElementById('cpu').textContent = data.cpu;
            document.getElementById('memory').textContent = data.memory;
        }, 1000);
    </script>
</body>
</html>

运行python app.py后,访问http://服务器IP:5000即可查看实时资源使用情况。

3. 利用Supervisor管理Python进程
Supervisor是进程管理工具,可确保Python脚本持续运行,并在崩溃时自动重启。示例配置:

  • 安装Supervisor:sudo yum install -y supervisor
  • 创建配置文件(/etc/supervisor/conf.d/python_script.conf):
[program:my_python_script]
command=/usr/bin/python3 /path/to/your_script.py  # 替换为实际脚本路径
directory=/path/to/your_script_directory         # 脚本工作目录
autostart=true                                   # 开机自启
autorestart=true                                 # 崩溃自动重启
stderr_logfile=/var/log/my_python_script.err.log # 错误日志路径
stdout_logfile=/var/log/my_python_script.out.log # 输出日志路径
  • 启动Supervisor并加载配置:
sudo systemctl start supervisord
sudo supervisorctl reread  # 重新读取配置
sudo supervisorctl update  # 更新进程列表
sudo supervisorctl status  # 查看进程状态

通过supervisorctl命令可手动启动/停止进程,日志文件可用于排查脚本运行问题。

4. 使用Glances工具监控系统与Python进程
Glances是基于Python的跨平台监控工具,支持CPU、内存、磁盘、网络及Python进程的实时监控。示例步骤:

  • 安装Glances:sudo yum install -y epel-release && sudo yum install -y glances
  • 启动Glances:
    • 终端模式:glances(按q退出)
    • Web模式:glances -w(访问http://服务器IP:61208
      Glances会自动显示系统中运行的Python进程及其资源占用(CPU、内存、线程数等),支持排序和过滤。

5. 使用Prometheus+Grafana实现高级监控
Prometheus用于收集时序数据,Grafana用于数据可视化,适合大规模Python应用监控。示例步骤:

  • 安装Prometheus:下载并配置prometheus.yml,添加Python应用的监控目标(如job_name: 'python_app', static_configs: [{'targets': ['localhost:5000']}])
  • 在Python应用中集成prometheus_client库(pip install prometheus_client),暴露指标:
from prometheus_client import start_http_server, Gauge
import random
import time

# 定义指标
cpu_usage = Gauge('python_app_cpu_usage', 'Python应用CPU使用率')
memory_usage = Gauge('python_app_memory_usage', 'Python应用内存使用率')

# 模拟数据收集
start_http_server(5000)  # 启动HTTP服务器,暴露指标
while True:
    cpu_usage.set(random.uniform(10, 50))  # 模拟CPU使用率
    memory_usage.set(random.uniform(20, 60))  # 模拟内存使用率
    time.sleep(5)
  • 安装Grafana并配置Dashboard,导入Prometheus数据源,创建面板展示CPU、内存等指标的趋势图。

6. 使用Py-spy进行性能分析
Py-spy是无侵入的Python性能分析工具,可生成火焰图,帮助定位Python代码的性能瓶颈。示例步骤:

  • 安装Py-spy:pip install py-spy
  • 生成火焰图:
py-spy record -o profile.svg --pid $(pgrep -f your_script.py)

生成的profile.svg文件可通过浏览器打开,显示函数调用的耗时占比,帮助优化慢函数。

0