Python io 模块的 TextIOWrapper 或 BuffereRWPair 函数不能很好地与 pySerial 配合使用

标签 python io pyserial python-unicode

我正在为一些科学硬件编写串行适配器,其 command set使用 UTF-8 字符编码。来自硬件的所有响应都以回车符 (u'\r') 终止。我希望能够使用带有指定 EOL 字符的 pySerial 的 readline() 函数,所以我有这个设置,ala this thread :

import serial
import io

ser = serial.Serial(port='COM10', baudrate=128000)
sio = io.TextIOWrapper(io.BufferedRWPair(ser, ser, 1), encoding='utf-8', newline=u'\r')

ser.open()

# these commands move to coordintes (25000, 0, 25000)
cmd = 'M\x80\x1a\x06\x00\x00\x00\x00\x00\x80\x1a\x06\x00'
ucmd = u'M\x80\x1a\x06\x00\x00\x00\x00\x00\x80\x1a\x06\x00'

#this works
ser.write(cmd)
print sio.readline()

#this does not
sio.write(ucmd)
sio.flush()
print sio.readline()

奇怪的是,第一个命令字符串(直接使用 pySerial 的非 unicode)从硬件中引发了正确的行为。第二个(通过 Python 的 io 模块的 unicode)导致它不规则地移动然后挂起。为什么会这样?向硬件发送 unicode 命令字符串确实有效IF 命令字符串只有几个字符。一旦您开始发送具有 hex(ord(byte)) 值 > 0x7F(超出 ASCII 范围)的字节,您就会开始遇到麻烦。我可以毫不费力地解决这个问题,但想知道发生了什么。谢谢!

最佳答案

来自 io docs :

BufferedRWPair does not attempt to synchronize accesses to its underlying raw streams. You should not pass it the same object as reader and writer; use BufferedRandom instead.

我猜这是你的问题,因为你正在传递相同的对象 ser 作为 reader 和 writer。 BufferendRandom 看起来也不太符合要求。

那么您的 serial 问题是在等待 EOL 时挂起吗?

关于Python io 模块的 TextIOWrapper 或 BuffereRWPair 函数不能很好地与 pySerial 配合使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24498048/

相关文章:

java - 为什么我在写入的文件正常时却在屏幕上看到此输出?

Python 属性错误 : module 'serial' has no attribute 'Serial'

python - pyserial:没有名为工具的模块

python - 属性错误 : 'Settings' object has no attribute 'DATABASE_ENGINE'

python - Cython OpenMP 编译器标志

java - 为什么OutputStream write方法在PrintWriter的println方法之前打印?

java - 什么是输入流和输出流?我们为什么以及何时使用它们?

python - PyQt5 - 自动化串行模块

python - 在 Python DataFrame 中拆分字符串

python请求json返回单引号