在 python 2.x 中,我可以这样做:
import sys, array a = array.array('B', range(100)) a.tofile(sys.stdout)
然而,现在我得到了一个 TypeError: can't write bytes to text stream。是否有一些我应该使用的秘密编码?
TypeError: can't write bytes to text stream
import os os.write(1, a.tostring())
或者,os.write(sys.stdout.fileno(), …),如果它比 1对你来说更易读的话。
os.write(sys.stdout.fileno(), …)
1
更好的办法:
import sys sys.stdout.buffer.write(b"some binary data")
如果您希望在 python3中指定编码,那么您仍然可以使用 byte 命令,如下所示:
import os os.write(1,bytes('Your string to Stdout','UTF-8'))
其中1是 stdout —— > 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")
这样做的一种惯用方法是:
with os.fdopen(sys.stdout.fileno(), "wb", closefd=False) as stdout: stdout.write(b"my bytes object") stdout.flush()
好的方面是它使用普通的文件对象接口,这是 Python 中大家都习惯的。
注意,我正在设置 closefd=False,以避免在退出 with块时关闭 sys.stdout。否则,您的程序将无法再打印到标准输出。但是,对于其他类型的文件描述符,您可能希望跳过该部分。
closefd=False
with
sys.stdout