2023年12月13日发(作者:)

linuxcpu温度代码,linuxCPU温度

linux下一切皆文件,那么`CPU温度`的描述文件保存在哪呢?

要查看`有关温度`的东西,我们可以去`/sys/class/thermal`下查找:

```bash

~# ls

cooling_device0 cooling_device2 cooling_device4 cooling_device6 cooling_device8 thermal_zone0 thermal_zone2

cooling_device1 cooling_device3 cooling_device5 cooling_device7 cooling_device9 thermal_zone1

```

那么,这里哪个是描述`CPU`的温度呢?答案是包含在`thermal_zone*/temp`中,那么到底是哪个呢?我们先看下

`thermal_zone*/type`这个文件:

```bash

~# cat thermal_zone0/type thermal_zone2/type thermal_zone2/type

acpitz

acpitz

x86_pkg_temp

```

看出区别了?没错,就是`x86_pkg_temp`。所以,要获得`CPU温度`,需要先查看`/sys/class/thermal/thermal_zone*/type`文件是

否为`x86_pkg_temp`,然后在查看相应的`/sys/class/thermal/thermal_zone*/temp`文件。(注: 将temp文件里面的数值除以1000

就是相应的`CPU`的摄氏温度)。

附`python`代码:

```python

def cpu_temp():

BASE_PATH = '/sys/class/thermal/'

resl = list()

for f in r(BASE_PATH):

if f[0:12] == 'thermal_zone':

temp_path = (BASE_PATH, f, 'temp')

type_path = (BASE_PATH, f, 'type')

if (temp_path) and (type_path):

with open(temp_path, 'r') as fp:

temp_tmp = float(())/1000

with open(type_path, 'r') as fp:

type_tmp = ()

if type_() == 'x86_pkg_temp':

(temp_tmp)return resl```