问题:如何在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。我应该使用一些秘密编码吗?

In python 2.x I could do this:

import sys, array
a = array.array('B', range(100))
a.tofile(sys.stdout)

Now however, I get a TypeError: can't write bytes to text stream. Is there some secret encoding that I should use?


回答 0

更好的方法:

import sys
sys.stdout.buffer.write(b"some binary data")

A better way:

import sys
sys.stdout.buffer.write(b"some binary data")

回答 1

import os
os.write(1, a.tostring())

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

import os
os.write(1, a.tostring())

or, os.write(sys.stdout.fileno(), …) if that’s more readable than 1 for you.


回答 2

只能在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块时关闭。否则,您的程序将无法再打印到标准输出。但是,对于其他类型的文件描述符,您可能要跳过该部分。

An idiomatic way of doing so, which is only available for Python 3, is:

with os.fdopen(sys.stdout.fileno(), "wb", closefd=False) as stdout:
    stdout.write(b"my bytes object")
    stdout.flush()

The good part is that it uses the normal file object interface, which everybody is used to in Python.

Notice that I’m setting closefd=False to avoid closing sys.stdout when exiting the with block. Otherwise, your program wouldn’t be able to print to stdout anymore. However, for other kind of file descriptors, you may want to skip that part.


回答 3

如果您想在python3中指定编码,则仍然可以使用bytes命令,如下所示:

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")

In case you would like to specify an encoding in python3 you can still use the bytes command like below:

import os
os.write(1,bytes('Your string to Stdout','UTF-8'))

where 1 is the corresponding usual number for stdout –> sys.stdout.fileno()

Otherwise if you don’t care of the encoding just use:

import sys
sys.stdout.write("Your string to Stdout\n")

If you want to use the os.write without the encoding, then try to use the below:

import os
os.write(1,b"Your string to Stdout\n")

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。