簡體   English   中英

在 try-except 結構中,無法編譯和返回 Python 函數

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM