简体   繁体   English

在 try-except 结构中,无法编译和返回 Python 函数

[英]Unable to compile and return for a Python function, in a try-except structure

I did debug the code below, line-by-line using some print statements.我确实使用一些打印语句逐行调试了下面的代码。

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

Everything looks OK until the line:一切看起来都不错,直到这一行:

return Serial(params[0], int(params[1]), flush=True, debug=debug)

this line is supposed to be compiled since all the objects in the Serial like params[0] , etc are obtained.由于获得了Serial中的所有对象(如params[0]params[0] ,因此应该编译此行。 But it returns an error jumping to the except and printing the statement "ERROR: Unable to initialize a serial connection to ..."但它返回一个错误跳转到except并打印语句"ERROR: Unable to initialize a serial connection to ..."

I am using Python 3.6.8 on a Docker container.我在 Docker 容器上使用 Python 3.6.8。

Any kind of help would be appreciated.任何形式的帮助将不胜感激。 I'm ready for any further info, if needed.如果需要,我已准备好提供任何进一步的信息。

Here, I post the Serial .在这里,我发布了Serial I hope this helps you guys to better understand my issue.我希望这可以帮助你们更好地理解我的问题。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM