有没有更自动化的方法来发现子字符串?



我正在尝试从设备中提取温度,并通过串行发送命令以获取机器的响应。 响应(也称为字符串(b'wf_test m_temp rnmain card temp=31500 (31.5 oC)rn[root@testest:~]# rn[root@testest:~]# '

下面的代码正在工作,我只是想知道如何使其更具移动性(这意味着我可以将其用于其他机器,以提取它们的温度,而无需更改位置参数以在正确的位置切片字符串(。我尝试了find方法,但它只是给了我字符串的位置,我不确定如何继续。现在,代码对包含温度字符串 (31.5( 的字符串进行切片并进行比较。

import serial
from time import sleep
ser = serial.Serial('COM3', timeout=1)
ser.baudrate = 115200

def temp_read ():
temp = b"wf_test m_temp rn"
ser.write(temp)
result = ser.read(1000)
print(result)
str1 = str(result)
str1.find('(')
str2 = str1[43:47]
print(str2 +' oC')
float(str2)
if float(str2) < 70:
print('Pass')
else:
print('Fail')

我希望能够发现绳子的oC并向后切,以便我可以获得温度并进行比较。

你可以在这里使用正则表达式,例如尝试使用re.findall

inp = "wf_test m_temp rnmain card temp=31500 (31.5 oC)rn[root@testest:~]# rn[root@testest:~]# "
temps = re.findall(r'((d+(?:.d+)?) oC)', inp)
print(temps)

这将打印:

['31.5']

((d+(?:.d+)?) oC)使用的正则表达式模式将针对每个显示为(31.5 oC)的温度。

编辑:

使用以下方法获取整数温度:

temps = re.findall(r'btemp=(d+)', inp)

您可以使用正则表达式来识别模式"rn", label, "=", digits(即"rnmain card temp=31500"( 在结果中。

在下文中,matches是在字符串中找到的所有温度的列表。通常应该只有一个匹配项。所以这将打印:"main card temp: Pass"作为您的示例输入。

import re
import serial
from time import sleep
ser = serial.Serial('COM3', timeout=1)
ser.baudrate = 115200
def temp_read():
ser.write(b"wf_test m_temp rn")
result = ser.read(1000).decode()
matches = re.findall(r"rn([^=]+)=(d+)", result)
if matches:
# matches will be like [('main card temp', '31500')]
label = matches[0][0]
temp = int(matches[0][1]) / 1000
print(label + ': ' + ('Pass' if temp < 70 else 'Fail'))
else:
print('No temperature found in "%s"' % result)

表达式为

rn        # CR + LF
([^=]+)     # group 1 (label): multiple characters other than "="
=           # "="
(d+)       # group 2 (temp): multiple digits

相关内容

最新更新