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

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“,这很奇怪,因为它在Python 2.7中有效。有什么主意吗?

理想情况下,我应该只能在可用时读取串行数据。每1,000毫秒发送一次数据。

最佳答案

将其放在单独的线程中,例如:

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

关于python - PySerial非阻塞读取循环,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17553543/

10-16 22:55