利用python和必要的库,实时监测计算机的基本运行参数:温度
时间: 2023-12-03 19:43:05 浏览: 34
要实时监测计算机的温度,可以使用Python中的psutil库和pymon库。以下是一个简单的示例代码:
```python
import psutil
import time
from pymon import sensors
while True:
# 使用psutil库获取CPU温度
cpu_temp = psutil.sensors_temperatures()['coretemp'][0].current
# 使用pymon库获取GPU温度
gpu_temp = sensors.nvidia_smi().GPUs[0].temperature.gpu
print(f"CPU Temperature: {cpu_temp}°C")
print(f"GPU Temperature: {gpu_temp}°C")
time.sleep(1)
```
在上面的代码中,我们使用psutil库来获取CPU温度,并使用pymon库获取GPU温度。我们在一个无限循环中不断地打印出这些温度值,并使用time库来使程序每秒钟更新一次温度值。
相关问题
linux系统利用python和必要的库,实时监测计算机的基本运行参数:如CPU负荷、内存占用率、温度
可以使用Python标准库中的psutil和sensors模块来实时监测计算机的基本运行参数,以下是一个例子:
```python
import psutil
import sensors
# 获取CPU负载和内存占用率
cpu_percent = psutil.cpu_percent(interval=1)
mem_percent = psutil.virtual_memory().percent
# 获取CPU温度
sensors.init()
try:
for chip in sensors.iter_detected_chips():
if chip.prefix == 'coretemp':
for feature in chip:
if 'temp' in feature.label:
cpu_temp = feature.get_value()
break
except Exception as e:
print(e)
finally:
sensors.cleanup()
print("CPU负载:{}%".format(cpu_percent))
print("内存占用率:{}%".format(mem_percent))
print("CPU温度:{}℃".format(cpu_temp))
```
其中,psutil.cpu_percent(interval=1)获取的是过去1秒钟的CPU负荷平均值,psutil.virtual_memory().percent获取的是当前内存占用率。而sensors模块可以获取计算机的各种传感器信息,包括CPU温度。需要注意的是,sensors模块可能需要root权限才能够正常工作,如果出现权限问题可以尝试给当前用户授权或使用sudo执行。
利用python和必要的库,实时监测计算机的基本运行参数:如CPU负荷、内存占用率、温度等等,每秒获取一次数据,然后保存到一个excel表格文件中,连续监测600秒。在首行需要添加参数文字说明。文件名称格式:年月日时分秒;
好的,你需要安装psutil和openpyxl库。可以使用以下命令进行安装:
```
pip install psutil
pip install openpyxl
```
接下来是代码实现:
```python
import psutil
import openpyxl
from datetime import datetime
from time import sleep
# 创建Excel文件及表格
wb = openpyxl.Workbook()
ws = wb.active
ws.title = "系统运行参数"
# 定义参数名称
params = ['时间', 'CPU占用率(%)', 'CPU温度(℃)', '内存占用率(%)']
# 添加参数名称到第一行
for i, param in enumerate(params):
ws.cell(row=1, column=i+1, value=param)
# 循环监测,每秒获取一次数据
for i in range(600):
# 获取当前时间
now = datetime.now()
time_str = now.strftime("%Y%m%d%H%M%S")
# 获取CPU占用率和温度
cpu_percent = psutil.cpu_percent()
cpu_temp = psutil.sensors_temperatures()['coretemp'][0].current
# 获取内存占用率
mem = psutil.virtual_memory()
mem_percent = mem.percent
# 将参数值添加到表格中
ws.append([time_str, cpu_percent, cpu_temp, mem_percent])
# 保存Excel文件
wb.save(time_str+'.xlsx')
# 等待1秒
sleep(1)
# 关闭Excel文件
wb.close()
```
运行完毕后,每秒钟获取一次计算机的基本运行参数,保存到一个excel表格文件中,并且连续监测了600秒。