树莓派CPU温度浮点值提取:更优雅可靠的Python实现方案
更Pythonic的树莓派CPU温度提取方法?
在运行Raspbian 8.0 Jessie的树莓派上,我们可以用以下代码获取CPU温度:
import commands err, msg = commands.getstatusoutput('vcgencmd measure_temp') if not err: print(msg)
执行后会返回格式类似 temp=47.2'C 的字符串(用单引号替代温度符号)。目前你用这段代码将其转换为浮点值:
print(float(msg.split('=')[1].split("'")[0]))
确实能正常返回47.2,但确实有更优雅、更符合Python风格的实现方式,下面给你几个选项:
1. 正则表达式提取(简洁直观)
因为返回的字符串格式非常固定,用正则匹配数字部分是最直接的方式,代码更紧凑:
import re import commands err, msg = commands.getstatusoutput('vcgencmd measure_temp') if not err: temp = float(re.search(r'\d+\.\d+', msg).group()) print(temp)
\d+\.\d+ 会精准匹配带小数点的温度数值,不管前后的字符内容,只要输出格式不变就非常可靠。
2. 使用partition方法(可读性更强)
相比多次split,partition方法会明确把字符串按分隔符拆成三部分,逻辑更清晰,可读性更好:
import commands err, msg = commands.getstatusoutput('vcgencmd measure_temp') if not err: # 先按=分割,取后面的部分;再按'分割,取前面的数值字符串 temp_str = msg.partition('=')[2].partition("'")[0] temp = float(temp_str) print(temp)
这种方式不需要记住split后的索引位置,代码逻辑一目了然。
3. 升级到现代Python的subprocess模块(兼容+可靠)
注意commands模块在Python 3中已经被弃用了,官方推荐使用subprocess模块来执行外部命令,同时加上异常处理,让代码更健壮:
import subprocess import re try: # 执行命令并获取输出,text=True让输出直接是字符串 output = subprocess.check_output(['vcgencmd', 'measure_temp'], text=True) temp = float(re.search(r'\d+\.\d+', output).group()) print(temp) except subprocess.CalledProcessError: print("获取CPU温度失败")
这个版本不仅更符合现代Python的规范,还能处理命令执行失败的情况,可靠性大幅提升。
内容的提问来源于stack exchange,提问作者uhoh
相关产品推荐
相关产品推荐

