在 python 2.x 中,我可以这样做:
import sys, array
a = array.array('B', range(100))
a.tofile(sys.stdout)
然而,现在我得到了一个TypeError: can't write bytes to text stream
. 我应该使用一些秘密编码吗?
在 python 2.x 中,我可以这样做:
import sys, array
a = array.array('B', range(100))
a.tofile(sys.stdout)
然而,现在我得到了一个TypeError: can't write bytes to text stream
. 我应该使用一些秘密编码吗?
更好的方法:
import sys
sys.stdout.buffer.write(b"some binary data")
import os
os.write(1, a.tostring())
或者,os.write(sys.stdout.fileno(), …)
如果这比1
您更具可读性。
这样做的惯用方式(仅适用于 Python 3)是:
with os.fdopen(sys.stdout.fileno(), "wb", closefd=False) as stdout:
stdout.write(b"my bytes object")
stdout.flush()
好的部分是它使用普通的文件对象接口,每个人在 Python 中都习惯了。
请注意,我设置closefd=False
为避免sys.stdout
在退出with
块时关闭。否则,您的程序将无法再打印到标准输出。但是,对于其他类型的文件描述符,您可能希望跳过该部分。
如果您想在 python3 中指定编码,您仍然可以使用 bytes 命令,如下所示:
import os
os.write(1,bytes('Your string to Stdout','UTF-8'))
其中 1 是标准输出对应的常用编号 --> sys.stdout.fileno()
否则,如果您不关心编码,请使用:
import sys
sys.stdout.write("Your string to Stdout\n")
如果您想使用没有编码的 os.write,请尝试使用以下内容:
import os
os.write(1,b"Your string to Stdout\n")