【问题标题】:Unable to compile and return for a Python function, in a try-except structure无法在 try-except 结构中编译并返回 Python 函数
【发布时间】:2021-06-30 20:22:19
【问题描述】:

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

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]等都已获取。但它返回错误跳转到except 并打印语句"ERROR: Unable to initialize a serial connection to ..."

我在 Docker 容器上使用 Python 3.6.8。

我们将不胜感激任何形式的帮助。如果需要,我已准备好获取更多信息。

【问题讨论】:

  • 您传递给getSource() 的参数是什么?另外,您可以使用其他工具(如 Putty)打开该 docker 容器中的相应串行端口吗?这很可能是 docker 容器本身的问题。看看这里stackoverflow.com/a/24231872/12661819
  • 什么是Serial?您传递的参数的值究竟是多少?
  • @quamrana Serial 是在同一代码中定义的类。所有参数都是通过解析serial@/dev/ttyUSB0:115200得到的。 /dev/ttyUSB0 是与 telosb mote 关联的端口,115200 是波特率。
  • @DominikBerse 参数是comm,相当于serial@/dev/ttyUSB0:115200,在这里。当我在 docker 终端中传递这个命令时:python filename.py serial@/dev/ttyUSB0:115200
  • 裸露的except: 绝不是一个好主意。将其设为except Exception as e:,并在您的输出中包含e - 它可能会准确地告诉您出了什么问题。

标签: python python-3.x pyserial try-except tinyos


【解决方案1】:

在这里,我发布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

【讨论】:

    猜你喜欢
    • 2011-01-22
    • 1970-01-01
    • 1970-01-01
    • 2020-11-10
    • 2018-11-06
    • 2011-05-08
    • 2013-04-13
    • 2019-06-26
    • 2013-11-12
    相关资源
    最近更新 更多