python bool转string_Python:可以返回boolean和string吗?
原始問題
我已經(jīng)創(chuàng)建了一個等待特定字符串出現(xiàn)在串行端口上的函數(shù),并返回所有字符讀取,直到找到該字符串,否則返回false.這很方便,但我想知道它是否被認為是不好的做法?
澄清:
主要目標是等待特定字符串在給定的時間內(nèi)出現(xiàn).除IO錯誤外,可能的結(jié)果為True(字符串確實出現(xiàn))或False
次要目標是獲取整個輸出,因為在尋找實際答案之前可能存在我想要解析的信息.我想可能是我可以在一個返回值中組合主要和次要目標.
def MyFunc(s, timeout) :
test = get_some_input(timeout)
if test.endswith(s)
return test
else
return False
編輯:另一個建議的答案是提出異常.我認為這不是一個好主意,因為超時是預期的行為.我的意思是,如果有一個用于指定超時的參數(shù),那么超時是可能的結(jié)果,而不是例外.
編輯2:
由于我需要存儲輸入,因此使用類是正確的解決方案. wait for函數(shù)具有明確的返回值,但是也可以訪問在超時之前讀取的整個字符串.
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
總結(jié)
以上是生活随笔為你收集整理的python bool转string_Python:可以返回boolean和string吗?的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
                            
                        - 上一篇: vue 2个方法先后执行_有效快速制作工
 - 下一篇: vvv在线文档导出工具_一款真正实时的在