在蟒蛇2.x的我能做到这一点:如何在python 3的stdout中编写二进制数据?
import sys, array
a = array.array('B', range(100))
a.tofile(sys.stdout)
但是现在,我得到一个TypeError: can't write bytes to text stream
。我应该使用一些秘密编码吗?
在蟒蛇2.x的我能做到这一点:如何在python 3的stdout中编写二进制数据?
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
你更具可读性。
谢谢,这工作。感觉有点黑客,但我想这不是一件常见的事情。 – 2009-05-25 23:21:54
`os.write`的问题是你必须检查返回值,因为它不能保证所有内容都会被写入。 – 2015-09-01 18:04:50
如果你想指定python3编码仍然可以使用的字节命令象下面这样:
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")
这将是更好的找到一个答案,将与Python 2.6 + 3合作。 x – sorin 2010-06-14 17:19:54
`os.write`可以在Py2和Py3上运行。 – 2014-04-26 17:50:40