我正在尝试通过串行端口对两个设备之间的通信进行简单的仿真(在Linux上非常清楚)。我想出了将从串行端口读取到不同线程中的想法,但是问题是该线程向我抛出了这样的错误:
Is open? True
Exception in thread Thread-1:
Traceback (most recent call last):
File "/usr/lib/python3.7/threading.py", line 926, in _bootstrap_inner
self.run()
File "/usr/lib/python3.7/threading.py", line 870, in run
self._target(*self._args, **self._kwargs)
File "client.py", line 18, in func
if len(ser.readline()) > 0:
File "/home/bartosz/PycharmProjects/socket-serial-comm/venv/lib/python3.7/site-packages/serial/serialposix.py", line 478, in read
raise portNotOpenError
serial.serialutil.SerialException: Attempting to use a port that is not open
因此,我尝试使用的端口似乎未打开,但是当我从该线程print("Is open? ", ser.is_open)
打印时,它给出了True,因此我无法在线程中打开该端口。
这是我的代码:
import serial
import threading
import time
ser = serial.Serial('/dev/pts/0', timeout=1)
def func():
print("Is open? ", ser.is_open)
while True:
if len(ser.readline()) > 0:
print(ser.readline())
x = threading.Thread(target=func, args=ser)
x.start()
time.sleep(1)
ser.write(b'some text\n')
time.sleep(1)
ser.close()
任何想法为什么会这样表现?
这与您编写的代码完全一样。
正在读取串行端口的进程永远以While True:
无限循环运行,但是端口本身是ser.close()
,大约在处理线程启动后2秒。因为即使在ser.readline()
之后仍执行ser.close()
,所以会出现问题错误。
在调用ser.close()
之前,您需要安装一种机制来终止def func():
线程处理。
顺便说一句,在len(ser.readline())
语句中先以if
进行判断,然后再以print(ser.readline())
进行判断,有数据需要输入两行,但第一行未显示,只打印该行会很奇怪下一行。
您应该查看该过程。