【问题标题】:Error/exception handling in imported Python module/library that uses threading使用线程的导入 Python 模块/库中的错误/异常处理
【发布时间】:2021-08-16 18:26:57
【问题描述】:

我正在使用 python 库,该库又使用 pyserial 与设备通信。有时我会遇到源自 pyserial 的异常,并在 SO 上多次提及:

错误:读取失败:设备报告已准备好读取但没有返回 数据(设备断开连接或端口上的多次访问?) Traceback(大多数 最近通话最后):文件 “/usr/lib/python3/dist-packages/serial/serialposix.py”,第 490 行,在 读 '设备报告已准备好读取但未返回数据' serial.serialutil.SerialException:设备报告已准备好读取 但没有返回数据(设备断开连接或端口上的多个访问?)

该错误是由上述库生成的,我可以使用记录器设置将其路由到日志文件。除了那个例外,pyserial(以及库)显然失去了与串行端口的连接。

我想做的是在收到该错误后恢复该连接。但是该库使用线程并且仅在接收串行通信事件时为我提供回调函数。所以我相信,没有办法使用 try/except,特别是考虑到该库似乎处理该异常以记录错误。

所以我的想法是在记录器收到该错误时以某种方式得到通知,以及 .close() 和 .open() 连接。但是如何获得该通知?

或者有什么更好的方法吗?

【问题讨论】:

    标签: python exception pyserial


    【解决方案1】:

    我现在的看法:

    old_factory = logging.getLogRecordFactory()
    global record, record_msg
    ERROR = False
    record_msg = ''
    serial_error = "read failed: device reports readiness to read but returned no data " + \
                   "(device disconnected or multiple access on port?)"
    
    def record_factory(*args, **kwargs):
        global record, ERROR, record_msg
        record = old_factory(*args, **kwargs)
        if record.levelname=="ERROR":
            ERROR = True
            record_msg = str(record.msg)
    

    所以,从新的record_factory 我可以设置标志并执行一些其他操作。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-02-09
      • 1970-01-01
      • 2011-03-09
      • 2013-11-03
      • 2013-02-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多