如何在 python 3 中将二进制数据写入 stdout?
- 2025-03-18 08:55:00
- admin 原创
- 41
问题描述:
在 python 2.x 中我可以这样做:
import sys, array
a = array.array('B', range(100))
a.tofile(sys.stdout)
但是现在,我得到了一个TypeError: can't write bytes to text stream
。我应该使用一些秘密编码吗?
解决方案 1:
更好的方法:
import sys
sys.stdout.buffer.write(b"some binary data")
解决方案 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
块时关闭。否则,您的程序将无法再打印到标准输出。但是,对于其他类型的文件描述符,您可能希望跳过该部分。
解决方案 3:
import os
os.write(1, a.tostring())
或者,os.write(sys.stdout.fileno(), …)
如果这对1
你来说更具可读性。
解决方案 4:
如果你想在 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
")
如果您想使用不带编码的 os.write,请尝试使用以下命令:
import os
os.write(1,b"Your string to Stdout
")
相关推荐
热门文章
项目管理软件有哪些?
热门标签
曾咪二维码
扫码咨询,免费领取项目管理大礼包!
云禅道AD