How to write binary data to standard output 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 TypeError: can't write bytes to text stream . Is there a secret encoding that I should use?

+72
python
May 25 '09 at 23:04
source share
4 answers

The best way:

 import sys sys.stdout.buffer.write(b"some binary data") 
+118
May 26 '09 at a.m.
source share
 import os os.write(1, a.tostring()) 

or, os.write(sys.stdout.fileno(), …) if it is more readable than 1 for you.

+11
May 25 '09 at 23:11
source share

If you want to specify the encoding in python3, you can still use the bytes command as shown below:

 import os os.write(1,bytes('Your string to Stdout','UTF-8')) 

where 1 is the corresponding regular number for stdout β†’ sys.stdout.fileno ()

Otherwise, if you do not need only the encoding:

 import sys sys.stdout.write("Your string to Stdout\n") 

If you want to use os.write without encoding, try using below:

 import os os.write(1,b"Your string to Stdout\n") 
+1
Apr 13 '15 at 13:05
source share

The idiomatic way to do this, 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 regular file object interface that everyone is used to in Python.

Note that I set closefd=False to avoid closing sys.stdout when exiting the with block. Otherwise, your program will not be able to print to standard output. However, for other types of file descriptors, you can skip this part.

0
Jan 07 '19 at 11:44
source share



All Articles