This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

Title: write to stdout in binary mode - is it possible?
Type: crash Stage:
Components: Interpreter Core Versions: Python 3.0
Status: closed Resolution: fixed
Dependencies: Superseder:
Assigned To: Nosy List: benjamin.peterson, christian.heimes, georg.brandl, lopgok
Priority: normal Keywords:

Created on 2008-12-07 02:40 by lopgok, last changed 2022-04-11 14:56 by admin. This issue is now closed.

Messages (6)
msg77208 - (view) Author: jeff deifik (lopgok) Date: 2008-12-07 02:40
I have a program that needs to output binary data to stdout.
I don't want to convert it to a string.

for example something like
to write a byte with all the bits turned on.

When I try this, I get an error like:
  File "/usr/local/lib/python3.0/", line 1484, in write
TypeError: can't write bytes to text stream

I know I can open a file in 'wb' mode and write to it, but what
I want to do is somehow switch the mode of stdout to 'wb' mode.
I read lots of python 3 documentation, as well as searched without
finding a way.
msg77210 - (view) Author: Benjamin Peterson (benjamin.peterson) * (Python committer) Date: 2008-12-07 03:14
You can write to the underlying raw stream:

msg77215 - (view) Author: Georg Brandl (georg.brandl) * (Python committer) Date: 2008-12-07 08:16
Is that an official way? If yes, it needs to be documented.
msg77228 - (view) Author: Benjamin Peterson (benjamin.peterson) * (Python committer) Date: 2008-12-07 14:58
Documented in r67365.
msg77229 - (view) Author: jeff deifik (lopgok) Date: 2008-12-07 15:48
I don't consider sys.stdout.buffer.write(b'abc')
to be an acceptable solution. There are many programs that need
to produce binary output with standard output. Consider uudecode
and similar programs.

There needs to be a standard, portable, documented way to put stdout
into binary mode in order to write binary output. For example,
all the flavors of the print command need to be able to send binary
data to standard output.

I don't have a problem changing open statements to support binary
file i/o, but I do have a problem changing every print or write statement
in order to support binary file i/o.
msg77230 - (view) Author: Christian Heimes (christian.heimes) * (Python committer) Date: 2008-12-07 15:51
switch to binary mode
>>> sys.stdout = sys.stdout.buffer

switch back
>>> sys.stdout = sys.__stdout__
Date User Action Args
2022-04-11 14:56:42adminsetgithub: 48821
2008-12-07 15:51:10christian.heimessetnosy: + christian.heimes
messages: + msg77230
2008-12-07 15:49:00lopgoksetmessages: + msg77229
2008-12-07 14:58:27benjamin.petersonsetstatus: open -> closed
resolution: fixed
messages: + msg77228
2008-12-07 08:16:17georg.brandlsetnosy: + georg.brandl
messages: + msg77215
2008-12-07 03:14:59benjamin.petersonsetnosy: + benjamin.peterson
messages: + msg77210
2008-12-07 02:40:10lopgokcreate