バックグラウンド
write()
「wb」モードのファイル オブジェクトのメソッドは、メモリビューとバイトの両方をサポートします。
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()