Fix Python – How to write binary data to stdout in python 3?

Question

Asked By – Ivan Baldin

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?

Now we will see solution for issue: How to write binary data to stdout in python 3?


Answer

A better way:

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

This question is answered By – Benjamin Peterson

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0