@TOC
在现代软件开发中,了解系统的资源使用情况对于优化性能、监控系统状态以及进行故障排查至关重要。Python作为一种广泛使用的编程语言,提供了多种库来帮助开发者获取系统级别的信息。本文将深入探讨如何使用Python获取系统CPU和内存使用情况,包括原理机制、完整代码示例以及实际应用案例。
psutil库获取CPU和内存使用情况/proc文件系统直接读取系统信息psutil库获取CPU和内存使用情况psutil是一个跨平台的库,用于检索有关正在运行的进程和系统利用率(CPU、内存、磁盘、网络等)的信息。它提供了一组丰富的函数,使得获取系统信息变得非常简单。
import psutil
def get_cpu_memory_usage():
# 获取CPU使用率
cpu_percent = psutil.cpu_percent(interval=1)
# 获取内存使用情况
memory_info = psutil.virtual_memory()
memory_percent = memory_info.percent
return cpu_percent, memory_percent
if __name__ == "__main__":
try:
cpu, memory = get_cpu_memory_usage()
print(f"CPU Usage: {cpu}%")
print(f"Memory Usage: {memory}%")
except Exception as e:
print(f"An error occurred: {e}")psutil.cpu_percent(interval=1):返回CPU使用率,interval参数表示采样间隔时间。psutil.virtual_memory():返回一个包含内存使用情况的对象,可以通过.percent属性获取内存使用百分比。try-except块来捕获并处理可能发生的异常。/proc文件系统直接读取系统信息在Linux系统中,/proc文件系统提供了访问内核数据结构的接口。通过读取/proc目录下的特定文件,可以直接获取CPU和内存使用情况。
def get_cpu_memory_usage_from_proc():
# 获取CPU使用率
with open('/proc/stat', 'r') as f:
lines = f.readlines()
for line in lines:
if line.startswith('cpu '):
cpu_stats = [int(x) for x in line.split()[1:]]
total_idle = cpu_stats[3] + cpu_stats[4]
total = sum(cpu_stats)
break
cpu_percent = (total - total_idle) / total * 100
# 获取内存使用情况
with open('/proc/meminfo', 'r') as f:
meminfo = dict((i.split()[0].rstrip(':'), int(i.split()[1])) for i in f.readlines())
total_mem = meminfo['MemTotal']
free_mem = meminfo['MemFree'] + meminfo['Buffers'] + meminfo['Cached']
memory_percent = (total_mem - free_mem) / total_mem * 100
return cpu_percent, memory_percent
if __name__ == "__main__":
try:
cpu, memory = get_cpu_memory_usage_from_proc()
print(f"CPU Usage: {cpu:.2f}%")
print(f"Memory Usage: {memory:.2f}%")
except Exception as e:
print(f"An error occurred: {e}")/proc/stat:包含CPU统计信息,解析该文件可以计算CPU使用率。/proc/meminfo:包含内存统计信息,解析该文件可以计算内存使用率。在获取系统信息时,可能会遇到各种边界情况和异常,如文件不存在、权限不足、格式错误等。合理的异常处理机制是保证程序稳定运行的关键。
def safe_get_cpu_memory_usage():
try:
return get_cpu_memory_usage()
except Exception as e:
print(f"Error using psutil: {e}")
try:
return get_cpu_memory_usage_from_proc()
except Exception as e:
print(f"Error reading from /proc: {e}")
return None, None
if __name__ == "__main__":
cpu, memory = safe_get_cpu_memory_usage()
if cpu is not None and memory is not None:
print(f"CPU Usage: {cpu}%")
print(f"Memory Usage: {memory}%")
else:
print("Failed to retrieve CPU and memory usage.")try-except块分别处理psutil和/proc文件系统的方法。None。假设你在开发一个音乐流媒体平台“猴子音悦100万正版音乐”,需要实时监控服务器的CPU和内存使用情况,以确保系统稳定运行。
import time
import sqlite3
def store_cpu_memory_usage(cpu, memory):
conn = sqlite3.connect('system_monitor.db')
c = conn.cursor()
c.execute('''CREATE TABLE IF NOT EXISTS system_usage
(timestamp TEXT, cpu REAL, memory REAL)''')
c.execute("INSERT INTO system_usage (timestamp, cpu, memory) VALUES (?, ?, ?)",
(time.strftime('%Y-%m-%d %H:%M:%S'), cpu, memory))
conn.commit()
conn.close()
def monitor_system():
while True:
cpu, memory = safe_get_cpu_memory_usage()
if cpu is not None and memory is not None:
store_cpu_memory_usage(cpu, memory)
time.sleep(60) # 每分钟采集一次数据
if __name__ == "__main__":
monitor_system()sqlite3库将获取到的数据存储在SQLite数据库中。time.sleep(60)每分钟采集一次数据。本文详细介绍了如何使用Python获取系统CPU和内存使用情况,包括使用psutil库和/proc文件系统的方法。我们还讨论了如何处理边界情况和异常,并通过实际应用案例展示了如何在真实项目中应用这些技术。希望读者能够从本文中获得有价值的见解,并在实际开发中灵活运用这些知识。
本文深入探讨了如何使用Python获取系统CPU和内存使用情况深度好文的相关技术,从原理到实践,从基础到进阶,希望能够帮助读者全面掌握这一技术。
本文经过精心编写和优化,如有不准确之处,欢迎在评论区指出。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。