我正在读这样的串行数据:
connected = False
port = 'COM4'
baud = 9600
ser = serial.Serial(port, baud, timeout=0)
while not connected:
#serin = ser.read()
connected = True
while True:
print("test")
reading = ser.readline().decode()
问题是它阻止了其他任何事情的执行,包括bottle py web框架。添加sleep()
没有帮助。
将“while True”更改为“while ser.readline():”不会打印“test”,这很奇怪,因为它在Python2.7中工作。有什么问题吗?
理想情况下,我应该能够读取串行数据只有当它是可用的。每1000毫秒发送一次数据
我会警告不要在线程中使用阻塞IO。请记住,Python有一个GIL,一次只能执行一个线程。现在请注意,pyserial模块是访问串行端口的操作系统实现的包装器。这意味着它调用Python外部的代码。如果代码被阻塞,那么解释器也会被阻塞,Python程序甚至主线程都不会执行任何操作。
如果底层设备驱动程序没有很好地实现超时,甚至在使用非阻塞IO或基于超时的轮询时也可能发生这种情况。
更健壮的方法是将multiprocessing模块与queue一起使用。在单独的进程中运行串行读取代码。这将确保主线程和其他线程不会阻塞,并且程序可以以干净的方式退出。
把它放在一个单独的线程中,例如:
http://docs.python.org/3/library/threading
使用单独的线程是完全不必要的。只需在无限while循环中执行此操作(在Python 3.2.3中进行了测试):
这样你只有在有东西的时候才能阅读和打印。你说,“理想情况下,我应该能够读取串行数据只有当它可用。”这正是上面的代码所做的。如果没有可供读取的内容,它将跳到while循环中的其余代码。完全没有阻塞。
(此答案最初发布在此处调试:Python 3 non-blocking read with pySerial (Cannot get pySerial's "in_waiting" property to work))
pySerial文档:http://pyserial.readthedocs.io/en/latest/pyserial_api.html
更新:
in_waiting
与inWaiting()
的评论。感谢@FurkanTürkal在下面的评论中指出这一点。请参阅此处的文档:https://pyserial.readthedocs.io/en/latest/pyserial_api.html#serial.Serial.in_waiting。多线程注意事项:
尽管如上所示,读取串行数据不需要使用多个线程,但以非阻塞方式读取键盘输入也不需要。因此,为了实现无阻塞的键盘输入读取,我编写了这个答案:How to read keyboard-input?。
相关问题 更多 >
编程相关推荐