我是python编码的新手,我需要一个显示当前CPU温度的程序。我的CPU有4个核心,所以我做了以下程序。
#!/usr/bin/python
import subprocess
import re
sensor_data = subprocess.check_output('/usr/bin/sensors')
find_temp = re.search(r'Core 0:\s+\+([\d]+).*', sensor_data)
if find_temp:
core_0_temp = find_temp.groups()[0]
else:
core_0_temp = 0
find_temp = re.search(r'Core 1:\s+\+([\d]+).*', sensor_data)
if find_temp:
core_1_temp = find_temp.groups()[0]
else:
core_1_temp = 0
find_temp = re.search(r'Core 2:\s+\+([\d]+).*', sensor_data)
if find_temp:
core_2_temp = find_temp.groups()[0]
else:
core_2_temp = 0
find_temp = re.search(r'Core 3:\s+\+([\d]+).*', sensor_data)
if find_temp:
core_3_temp = find_temp.groups()[0]
else:
core_3_temp = 0
print core_0_temp, core_1_temp, core_2_temp, core_3_temp
有人可以就如何改进这个计划提出一些建议吗?
目前它有效,但我该怎么做才能改进这段代码?
boby@fwhlin:~/utils/cpu$ ./cpu_temp
49 48 48 46
boby@fwhlin:~/utils/cpu$
传感器命令的结果如下所示
boby@fwhlin:~/utils/cpu$ /usr/bin/sensors
atk0110-acpi-0
Adapter: ACPI interface
Vcore Voltage: +0.93 V (min = +0.80 V, max = +1.60 V)
+3.3V Voltage: +3.28 V (min = +2.97 V, max = +3.63 V)
+5V Voltage: +5.14 V (min = +4.50 V, max = +5.50 V)
+12V Voltage: +12.03 V (min = +10.20 V, max = +13.80 V)
CPU Fan Speed: 2721 RPM (min = 600 RPM, max = 7200 RPM)
Chassis1 Fan Speed: 0 RPM (min = 600 RPM, max = 7200 RPM)
Chassis2 Fan Speed: 0 RPM (min = 600 RPM, max = 7200 RPM)
NB Fan Speed: 1318 RPM (min = 600 RPM, max = 7200 RPM)
Power Fan Speed: 0 RPM (min = 0 RPM, max = 7200 RPM)
CPU Temperature: +56.0°C (high = +60.0°C, crit = +95.0°C)
MB Temperature: +60.0°C (high = +45.0°C, crit = +75.0°C)
NB Temperature: +56.5°C (high = +60.0°C, crit = +95.0°C)
coretemp-isa-0000
Adapter: ISA adapter
Core 0: +48.0°C (high = +80.0°C, crit = +100.0°C)
Core 1: +47.0°C (high = +80.0°C, crit = +100.0°C)
Core 2: +47.0°C (high = +80.0°C, crit = +100.0°C)
Core 3: +47.0°C (high = +80.0°C, crit = +100.0°C)
radeon-pci-0400
Adapter: PCI adapter
temp1: +57.0°C (crit = +120.0°C, hyst = +90.0°C)
boby@fwhlin:~/utils/cpu$
答案 0 :(得分:0)
你可以将它放在for循环中,并使用dict / list来存储值:
core_temps = {}
for core in range(4):
find_temp = re.search(r'Core %d:\s+\+([\d]+).*' % core, sensor_data)
if find_temp:
core_temps[core] = find_temp.groups()[0]
else:
core_temps[core] = 0
print core_temps
答案 1 :(得分:0)
我愿意
#!/usr/bin/python
import subprocess
import re
sensor_data = subprocess.check_output('/usr/bin/sensors')
find_temps = re.finditer(r'Core (\d*):\s+\+([\d]+).*', sensor_data)
temps = {}
for find_temp in find_temps:
index, temp = find_temp.group(1, 2)
temps[index] = temp
print temps
for k in sorted(temps.keys()):
print k, temps[k]
print
这将搜索所有Core XX:
行并将它们放入dict。