在Ubuntu 20.04的Python中解析psutil.sensors_temperatures()中()的内部值

2024-09-28 03:19:23 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我随身带着这个JSON字符串

`{'nvme': [shwtemp(label='Composite', current=45.85, high=79.85, critical=84.85)], 
'pch_cannonlake': [shwtemp(label='', current=62.0, high=None, critical=None)],
'iwlwifi_1': [shwtemp(label='', current=51.0, high=None, critical=None)],
'coretemp': [shwtemp(label='Package id 0', current=55.0, high=100.0, critical=100.0), 
    shwtemp(label='Core 0', current=55.0, high=100.0, critical=100.0),
    shwtemp(label='Core 1', current=53.0, high=100.0, critical=100.0),
    shwtemp(label='Core 2', current=53.0, high=100.0, critical=100.0),
    shwtemp(label='Core 3', current=51.0, high=100.0, critical=100.0)]}`

我正在使用Python从这个字符串中读取值。那么如何访问这个JSON中的shwtemp()和“label”

我已经尝试过varName['nvme']['shwtemp'],但显示错误

现在我从psutil.sensors_temperatures()获得了这个“JSON”

我想做的是在Ubuntu 20.04中获得python中的CPU临时值。所以任何改进都可能是巨大的


Tags: 字符串corenonejsoncurrentlabelhighcomposite
1条回答
网友
1楼 · 发布于 2024-09-28 03:19:23

您有一个包含一个或多个shwtemp的列表,您应该使用索引[0]来获取第一个元素或for-loop来分别处理每个元素

稍后您将看到对象shwtemp,它具有字段.current

data = psutil.sensors_temperatures()

print('First:', data['nvme'][0].current)

# or

for item in data['nvme']:
    print(item.current)

显示coretemp的最小工作示例(该示例具有更多值,因此for-loop似乎很有用)


import psutil

data = psutil.sensors_temperatures()
print('\n - type  -')
print(type(data))  # dict
print(' - value  -')
print(data)

core = data['coretemp']
print('\n - type  -')
print(type(core))  # list
print(' - value  -')
print(core)

item = core[0]
print('\n - type  -')
print(type(item))  # object shwtemp
print(' - value  -')
print(item)
print(' - fields  -')
print('label   :', item.label)
print('current :', item.current)
print('high    :', item.high)
print('critical:', item.critical)

#                         -

data = psutil.sensors_temperatures()

print('\n - First  -')
print('First:', data['coretemp'][0].current)

print('\n - for-loop  -')
for item in data['coretemp']:
    print(item.label, ':', item.current)

结果:

 - type  -
<class 'dict'>
 - value  -
{'acpitz': [shwtemp(label='', current=57.0, high=102.0, critical=102.0), shwtemp(label='', current=39.0, high=96.0, critical=96.0)], 'radeon': [shwtemp(label='', current=56.0, high=120.0, critical=120.0)], 'coretemp': [shwtemp(label='Core 0', current=58.0, high=95.0, critical=105.0), shwtemp(label='Core 2', current=60.0, high=95.0, critical=105.0)]}

 - type  -
<class 'list'>
 - value  -
[shwtemp(label='Core 0', current=58.0, high=95.0, critical=105.0), shwtemp(label='Core 2', current=60.0, high=95.0, critical=105.0)]

 - type  -
<class 'psutil._common.shwtemp'>
 - value  -
shwtemp(label='Core 0', current=58.0, high=95.0, critical=105.0)
 - fields  -
label   : Core 0
current : 58.0
high    : 95.0
critical: 105.0

 - First  -
First: 58.0

 - for-loop  -
Core 0 : 58.0
Core 2 : 60.0

相关问题 更多 >

    热门问题