How to write binary data to stdout in python 3?

Question:

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?

Asked By: Ivan Baldin

||

Answers:

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

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

Answered By: Alex Martelli

A better way:

import sys
sys.stdout.buffer.write(b"some binary data")
Answered By: Benjamin Peterson

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

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 Stdoutn")
Answered By: Marco smdm

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.

Answered By: Yajo
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.