Python获取 CPU 温度、CPU 占用、内存总空间、内存占用空间、系统磁盘总空间、系统磁盘占用空间等信息
先下载依赖
pip3 install psutil
代码
import psutil
# 获取 CPU 温度
def get_cpu_temperature():
try:
temperatures = psutil.sensors_temperatures()
if 'coretemp' in temperatures:
for entry in temperatures['coretemp']:
if entry.label == 'Package id 0':
return entry.current
except Exception as e:
print(f"Error getting CPU temperature: {e}")
return None
# 获取 CPU 占用
def get_cpu_usage():
return psutil.cpu_percent(interval=1)
# 获取内存总空间和内存占用空间
def get_memory_usage():
total_memory = psutil.virtual_memory().total
used_memory = psutil.virtual_memory().used
return total_memory, used_memory
# 获取系统磁盘总空间和系统磁盘占用空间
def get_disk_usage():
total_disk_space = psutil.disk_usage('/').total
used_disk_space = psutil.disk_usage('/').used
return total_disk_space, used_disk_space
# 示例用法
if __name__ == "__main__":
print("CPU 温度:", get_cpu_temperature(), "°C")
print("CPU 占用:", get_cpu_usage(), "%")
total_memory, used_memory = get_memory_usage()
print("内存总空间:", total_memory, "bytes")
print("内存占用空间:", used_memory, "bytes")
total_disk_space, used_disk_space = get_disk_usage()
print("系统磁盘总空间:", total_disk_space, "bytes")
print("系统磁盘占用空间:", used_disk_space, "bytes")
结果
CPU 温度: 45.0 °C
CPU 占用: 0.8 %
内存总空间: 3875471360 bytes
内存占用空间: 1162981376 bytes
系统磁盘总空间: 53660876800 bytes
系统磁盘占用空间: 14345547776 bytes