使用 pySerial 进行 Python 3 非阻塞读取(无法使 pySerial 的“in_waiting"属性起作用) [英] Python 3 non-blocking read with pySerial (Cannot get pySerial's "in_waiting" property to work)
问题描述
在我的一生中,我无法弄清楚如何使用我的 Raspberry Pi 在 Python 3 中进行非阻塞串行读取.
For the life of me, I cannot figure out how to do a non-blocking serial read in Python 3 using my Raspberry Pi.
这是我的代码:
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)
结果:AttributeError: 'Serial' 对象没有属性 'in_waiting'
这是我引用的参考页面,它告诉我in_waiting"存在:http://pyserial.readthedocs.io/en/latest/pyserial_api.html
Here's the reference page I'm referencing that told me "in_waiting" exists: http://pyserial.readthedocs.io/en/latest/pyserial_api.html
推荐答案
您列出的文档链接将 in_waiting
显示为 PySerial 3.0 中添加的属性.很可能您正在使用 PySerial <3.0 所以你必须调用 inWaiting()
函数.
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.
您可以通过以下方式查看 PySerial 的版本:
You can check the version of PySerial as follows:
import serial
print serial.VERSION
如果您使用 pip 安装了 PySerial,您应该能够执行升级(管理员权限可能需要):
If you installed PySerial using pip, you should be able to perform an upgrade (admin privileges may be required):
pip install --upgrade pyserial
否则,请更改您的代码以使用 PySerial < 中的正确接口.3.0:
Otherwise, change your code to use the proper interface from PySerial < 3.0:
while (True):
if (ser.inWaiting() > 0):
ser.read(ser.inWaiting())
这篇关于使用 pySerial 进行 Python 3 非阻塞读取(无法使 pySerial 的“in_waiting"属性起作用)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!