如何在Python 3中将二进制数据写入stdout?
在Python 2.x中,我可以这样做:
import sys, array
a = array.array('B', range(100))
a.tofile(sys.stdout)
但是现在我遇到了一个错误:TypeError: can't write bytes to text stream
。请问我应该使用什么特别的编码吗?
4 个回答
19
import os
os.write(1, a.tostring())
或者,你可以用 os.write(sys.stdout.fileno(), …)
这个方式,如果你觉得它比 1
更容易理解。
22
一种在Python 3中常用的方法是:
with os.fdopen(sys.stdout.fileno(), "wb", closefd=False) as stdout:
stdout.write(b"my bytes object")
stdout.flush()
这个方法的好处是,它使用了大家在Python中都很熟悉的普通文件对象接口。
请注意,我把closefd=False
设置为False,这样在退出with
块时就不会关闭sys.stdout
。否则,你的程序就无法再向标准输出打印内容了。不过,对于其他类型的文件描述符,你可能就不需要这么做了。
270
一种更好的方法:
import sys
sys.stdout.buffer.write(b"some binary data")