原始问题
我已经创建了一个等待特定字符串出现在串行端口上的函数,并返回所有字符读取,直到找到该字符串,否则返回false.这很方便,但我想知道它是否被认为是不好的做法?
澄清:
主要目标是等待特定字符串在给定的时间内出现.除IO错误外,可能的结果为True(字符串确实出现)或False
次要目标是获取整个输出,因为在寻找实际答案之前可能存在我想要解析的信息.我想可能是我可以在一个返回值中组合主要和次要目标.
def MyFunc(s, timeout) :
test = get_some_input(timeout)
if test.endswith(s)
return test
else
return False
编辑:另一个建议的答案是提出异常.我认为这不是一个好主意,因为超时是预期的行为.我的意思是,如果有一个用于指定超时的参数,那么超时是可能的结果,而不是例外.
编辑2:
由于我需要存储输入,因此使用类是正确的解决方案. wait for函数具有明确的返回值,但是也可以访问在超时之前读取的整个字符串.
class Parser :
def __init__(self, sport_name):
self.currentMsg = ''
self.ser = serial.Serial(sport_name, 115200)
def WaitFor(self, s, timeOut=None):
self.ser.timeout = timeOut
self.currentMsg = ''
while self.currentMsg.endswith(s) != True :
# should add a try catch here
c=self.ser.read()
if c != '' :
self.currentMsg += c
else :
print 'timeout waiting for ' + s
return False
return True