132

在 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

4 回答 4

208

更好的方法:

import sys
sys.stdout.buffer.write(b"some binary data")
于 2009-05-26T00:09:34.077 回答
16
import os
os.write(1, a.tostring())

或者,os.write(sys.stdout.fileno(), …)如果这比1您更具可读性。

于 2009-05-25T23:11:15.143 回答
15

这样做的惯用方式(仅适用于 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块时关闭。否则,您的程序将无法再打印到标准输出。但是,对于其他类型的文件描述符,您可能希望跳过该部分。

于 2019-01-07T11:44:50.930 回答
3

如果您想在 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")
于 2015-04-13T13:05:25.533 回答