[英]How to use try-except in Python function return boolean?
[英]Unable to compile and return for a Python function, in a try-except structure
我确实使用一些打印语句逐行调试了下面的代码。
class Timeout(Exception):
pass
def getSource(comm):
source = comm.split('@')
params = source[1].split(':')
debug = '--debug' in sys.argv
if source[0] == 'serial':
try:
return Serial(params[0], int(params[1]), flush=True, debug=debug)
except:
print ("ERROR: Unable to initialize a serial connection to", comm)
raise Exception
一切看起来都不错,直到这一行:
return Serial(params[0], int(params[1]), flush=True, debug=debug)
由于获得了Serial
中的所有对象(如params[0]
等params[0]
,因此应该编译此行。 但它返回一个错误跳转到except
并打印语句"ERROR: Unable to initialize a serial connection to ..."
我在 Docker 容器上使用 Python 3.6.8。
任何形式的帮助将不胜感激。 如果需要,我已准备好提供任何进一步的信息。
在这里,我发布了Serial
。 我希望这可以帮助你们更好地理解我的问题。
class Serial:
def __init__(self, port, baudrate, flush=False, debug=False, readTimeout=None, ackTimeout=0.02):
self.debug = debug
self.readTimeout = readTimeout
self.ackTimeout = ackTimeout
self._ts = None
if port.startswith('COM') or port.startswith('com'):
port = int(port[3:]) - 1
elif port.isdigit():
port = int(port) - 1
self._s = serial.Serial(port, int(baudrate), rtscts=0, timeout=0.5)
self._s.flushInput()
if flush:
print >>sys.stdout, "Flushing the serial port",
endtime = time.time() + 1
while time.time() < endtime:
self._s.read()
sys.stdout.write(".")
if not self.debug:
sys.stdout.write("\n")
self._s.close()
self._s = serial.Serial(port, baudrate, rtscts=0, timeout=readTimeout)
def getByte(self):
c = self._s.read()
if c == '':
raise Timeout
#print 'Serial:getByte: 0x%02x' % ord(c)
return ord(c)
def putBytes(self, data):
#print "DEBUG: putBytes:", data
for b in data:
self._s.write(struct.pack('B', b))
time.sleep(0.000001)
def getTimeout(self):
return self._s.timeout
def setTimeout(self, timeout):
self._s.timeout = timeout
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.