Python pySerial使用serial.Serial子类时串口永久阻塞问题求助
问题根因
你在自定义串口设备子类的__init__方法中多写了一行冗余的串口实例化代码:
class device1(serial.Serial): def __init__(self, port, timeout): super().__init__(port, timeout) serial.Serial(port, timeout) # 这行是多余的,直接导致问题
这行代码会重复打开当前端口,创建的临时serial.Serial对象没有被任何变量引用,执行完就会被Python垃圾回收,回收时自动触发串口关闭操作,直接导致你通过super().__init__初始化的当前子类实例的串口连接被意外关闭/重置。
第一个设备看起来正常是巧合:临时对象销毁关闭串口后,command1里的write操作触发了pyserial的隐性重连,而第二个设备的隐性重连没有正确恢复超时配置,导致readline进入无限等待。
解决方案
删除两个子类__init__方法中多余的serial.Serial(port, timeout)行即可,修正后的完整代码如下:
import serial class Device1(serial.Serial): def __init__(self, port, timeout): super().__init__(port, timeout=timeout) def command1(self): self.write(b'SET MUTE OFF\n') self.write(b'GET MUTE\n') output = self.readline() print("Device 1 output: " + str(output)) class Device2(serial.Serial): def __init__(self, port, timeout): super().__init__(port, timeout=timeout) def command2(self): self.write(b'00vP\r') output = self.readline() print("Device 2 output: " + str(output)) device1_port = "/dev/ttyUSB0" device2_port = "/dev/ttyUSB1" d1 = Device1(device1_port, timeout=0.5) d2 = Device2(device2_port, timeout=1) d1.command1() d2.command2()
验证说明
修改后再运行代码,两个设备都会正常返回结果,不会出现阻塞问题:
Device 1 output: b'DATA MUTE OFF\r\n' Device 2 output: b'00vP0\r'
内容的提问来源于stack exchange,提问作者rakix
相关产品推荐
相关产品推荐

