微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

我确实使用一些打印语句逐行调试了下面的代码

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],debug=debug)

这一行应该被编译,因为获得了 Serial 中的所有对象,如 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,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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。