PySerial非阻塞读循环

2024-09-30 01:21:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在读这样的串行数据:

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毫秒发送一次数据


Tags: 数据testfalsetruereadlineporttimeoutserial
3条回答

我会警告不要在线程中使用阻塞IO。请记住,Python有一个GIL,一次只能执行一个线程。现在请注意,pyserial模块是访问串行端口的操作系统实现的包装器。这意味着它调用Python外部的代码。如果代码被阻塞,那么解释器也会被阻塞,Python程序甚至主线程都不会执行任何操作。

如果底层设备驱动程序没有很好地实现超时,甚至在使用非阻塞IO或基于超时的轮询时也可能发生这种情况。

更健壮的方法是将multiprocessing模块与queue一起使用。在单独的进程中运行串行读取代码。这将确保主线程和其他线程不会阻塞,并且程序可以以干净的方式退出。

把它放在一个单独的线程中,例如:

import threading
import serial

connected = False
port = 'COM4'
baud = 9600

serial_port = serial.Serial(port, baud, timeout=0)

def handle_data(data):
    print(data)

def read_from_port(ser):
    while not connected:
        #serin = ser.read()
        connected = True

        while True:
           print("test")
           reading = ser.readline().decode()
           handle_data(reading)

thread = threading.Thread(target=read_from_port, args=(serial_port,))
thread.start()

http://docs.python.org/3/library/threading

使用单独的线程是完全不必要的。只需在无限while循环中执行此操作(在Python 3.2.3中进行了测试):

import serial
import time # Optional (if using time.sleep() below)

while (True):
    # NB: for PySerial v3.0 or later, use property `in_waiting` instead of function `inWaiting()` below!
    if (ser.inWaiting()>0): #if incoming bytes are waiting to be read from the serial input buffer
        data_str = ser.read(ser.inWaiting()).decode('ascii') #read the bytes and convert from binary array to ASCII
        print(data_str, end='') #print the incoming string without putting a new-line ('\n') automatically after every print()
    #Put the rest of your code you want here
    time.sleep(0.01) # Optional: sleep 10 ms (0.01 sec) once per loop to let other threads on your PC run during this time. 

这样你只有在有东西的时候才能阅读和打印。你说,“理想情况下,我应该能够读取串行数据只有当它可用。”这正是上面的代码所做的。如果没有可供读取的内容,它将跳到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

更新:

多线程注意事项:

尽管如上所示,读取串行数据不需要使用多个线程,但以非阻塞方式读取键盘输入也不需要。因此,为了实现无阻塞的键盘输入读取,我编写了这个答案:How to read keyboard-input?

相关问题 更多 >

    热门问题