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?
Join Stack Overflow to learn, share knowledge, and build your career.
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?
A better way:
import sys
sys.stdout.buffer.write(b"some binary data")
sys.stdout.buffer
also lets you do things like using shutil.copyfileobj
even when the source file object gives bytes, and not strings. +1
– csl
Jun 19 '15 at 14:45
AttributeError: 'PseudoOutputFile' object has no attribute 'buffer'
– Damian Yerrick
May 18 '17 at 18:55
pythonw.exe
runs IDLE, which means that there is no stdout. It is emulated with tkinter. It physically can't handle bytes. In this case, .decode('UTF-8', errors='replace')
your string, or run python3 -I <filename>
to get a REPL instead of using IDLE.
– Artyer
May 21 '17 at 11:41
stderr
if using along with print(file=sys.stderr)
.
– Kotauskas
Jul 19 '19 at 10:16
import os
os.write(1, a.tostring())
or, os.write(sys.stdout.fileno(), …)
if that's more readable than 1
for you.
os.write
is that you'll have to check the return value, as it doesn't guarantee that everything will be written.
– mic_e
Sep 1 '15 at 18:04
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.
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")
os.write(sys.stdout.fileno(), some_bytes)
won't work in IDLE. io.UnsupportedOperation: fileno
– Damian Yerrick
May 18 '17 at 18:57
stdout
, the last one.
– Kotauskas
Jul 19 '19 at 10:18
os.write
will work on both Py2 and Py3. – David Wolever Apr 26 '14 at 17:50