views:

352

answers:

2

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: 
import os
os.write(1, a.tostring())

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

Alex Martelli
Thanks, that worked. Feels a bit hack-ish but I guess it's not that common thing to do.
Ivan Baldin
+2  A: 

A better way:

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