How to write binary data to stdout in python 3?

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?


Solution 1:

A better way:

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

Solution 2:

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

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