Original Question
I have made a function which is waiting for a particular string to appear on a serial port, and returns all character read until the string was found, or false if not. This is quite convenient, but I was wondering if it is considered bad practice or not ?
Clarification :
The primary goal is to wait for a particular string to appear in a given amount of time. Except for IO error, the possible outcome is True (the string did appear) or False The secondary goal is to get the entire output, because there might be information that I would like to parse for before the actual answer that is looked for. I thought may be I could combine the primary and secondary goal in one return value.
def MyFunc(s, timeout) :
test = get_some_input(timeout)
if test.endswith(s)
return test
else
return False
Edit : Another proposed answer is to raise an exception. I don't think it is a good idea, because the timeout is an expected behaviour. I mean, if there is a parameter for specifying a timeout, then a timeout is a possible outcome, and not an exception.
Edit 2 : Since I need to store the input, maybe using a class is the right solution. The wait for function has a clear return value, yet the entire string that was read until timeout is also accessible.
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
Would it not be more suitable to return a None
instead of False
?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With