Python 3 non-blocking read with pySerial (Cannot get pySerial's “in_waiting” property to work)

喜欢而已 提交于 2019-12-10 18:15:53

问题


For the life of me, I cannot figure out how to do a non-blocking serial read in Python 3 using my Raspberry Pi.

Here's my code:

import serial #for pySerial

ser = serial.Serial('/dev/ttyUSB0', 9600) #open serial port
print ('serial port = ' + ser.name) #print the port used

while (True):
    if (ser.in_waiting>0):
        ser.read(ser.in_waiting)

Result:
AttributeError: 'Serial' object has no attribute 'in_waiting'

Here's the reference page I'm referencing that told me "in_waiting" exists: http://pyserial.readthedocs.io/en/latest/pyserial_api.html


回答1:


The documentation link you listed shows in_waiting as a property added in PySerial 3.0. Most likely you're using PySerial < 3.0 so you'll have to call the inWaiting() function.

You can check the version of PySerial as follows:

import serial
print serial.VERSION

If you installed PySerial using pip, you should be able to perform an upgrade (admin privileges may be required):

pip install --upgrade pyserial

Otherwise, change your code to use the proper interface from PySerial < 3.0:

while (True):
    if (ser.inWaiting() > 0):
        ser.read(ser.inWaiting())


来源:https://stackoverflow.com/questions/38757906/python-3-non-blocking-read-with-pyserial-cannot-get-pyserials-in-waiting-pro

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!