查看系统 CPU、磁盘、内存使用情况
python
from flask import Flask, jsonify
import psutil
import shutil
application = Flask(__name__)
@application .route('/status', methods=['GET'])
def get_system_status():
try:
# 获取CPU使用情况
cpu_usage = psutil.cpu_percent(interval=1)
# 获取磁盘使用情况(以根目录为例)
disk_usage = shutil.disk_usage("/")
disk_usage_percent = (disk_usage.used / disk_usage.total) * 100
disk_usage_readable = {
"total": f"{disk_usage.total / (1024**3):.2f} GB",
"used": f"{disk_usage.used / (1024**3):.2f} GB",
"free": f"{disk_usage.free / (1024**3):.2f} GB",
"percent": f"{disk_usage_percent:.2f}%"
}
# 获取内存使用情况
memory_usage = psutil.virtual_memory()
memory_usage_readable = {
"total": f"{memory_usage.total / (1024**3):.2f} GB",
"available": f"{memory_usage.available / (1024**3):.2f} GB",
"used": f"{memory_usage.used / (1024**3):.2f} GB",
"percent": f"{memory_usage.percent}%"
}
# 将结果打包成JSON返回
return jsonify({
"cpu_usage": cpu_usage,
"disk_usage": disk_usage_readable,
"memory_usage": memory_usage_readable
})
...
except Exception as e:
# 返回错误信息
return jsonify({"error": str(e), "trace": traceback.format_exc()}), 500
if __name__ == '__main__':
application.run(debug=True)