背景
“wb”模式的write()
文件对象方法同时支持memoryview和bytes:
v = memoryview("abc")
with open("txt.txt", "wb") as f:
f.write( v )
当我使用推荐的 pyserial 方法时readline()
:
import serial
import io
ser = serial.serial_for_url('loop://', timeout=1)
sio = io.TextIOWrapper(io.BufferedRWPair(ser, ser))
sio.write(unicode("hello\n"))
sio.flush() # it is buffering. required to get the data out *now*
hello = sio.readline()
print hello == unicode("hello\n")
它引发了错误:IOError: raw write() returned invalid length 22
.
我对此进行了调试,发现传递给ser.write()
from
的对象io.BufferedRWPair
是一个memoryview
对象。在ser.write()
它用于bytes(data)
转换传递对象的代码中,它得到类似“<memory at 0x061F54E0>”的内容。
问题
如果我需要实现write()
方法,那么使它可以同时处理对象的最佳方法是memoryview
什么bytes
?
以下是我想出的:
- 利用
isinstance()
data = memoryview(data).tobytes()