[docs] [issue18512] sys.stdout.write does not allow bytes in Python 3.x

Juan Luis Boya García report at bugs.python.org
Mon Aug 19 03:54:34 CEST 2013


Juan Luis Boya García added the comment:

Sorry for the late response, GMail's SPAM filter ate the replies.

The main issue is sys.stdout being opened as text instead of binary. This fact is stated in the docs. http://docs.python.org/3/library/sys.html#sys.stdout

In any case, there are some caveats worth noting:

> You can do
>    sys.stdout.buffer.write(b"hello")
This is problematic if both buffer and IOTextWrapper are used. For example:

  print("Hello", end=""); sys.stdout.buffer.write(b"World")

That line may write `WorldHello` instead of `HelloWorld` (and it does indeed, at least in Linux implementation).

Yes, an application should not do this in Python3, but using print() and writing to stdout were OK in Python2, which makes porting programs harder.

A workaround is to perform sys.stdout.flush() before sys.stdout.buffer.write().

> (from the docs)
> Using io.TextIOBase.detach(), streams can be made binary by default.
> sys.stdout = sys.stdout.detach()

This should help in cases where most output is binary, but it's worth noting that interactive shells (such as the builtin python or IPython) and debuggers (both pdb and ipdb) stop working when this is used. Also, it will probably break every function there that relies on sys.stdout being Unicode or binary depending on only the Python version.

----------

_______________________________________
Python tracker <report at bugs.python.org>
<http://bugs.python.org/issue18512>
_______________________________________


More information about the docs mailing list