printing bytes to stdout in Py3

Christian Heimes lists at cheimes.de
Tue Feb 17 12:33:41 EST 2009


Casey wrote:
> Is this really the 'official' way to do this?  This isn't meant to be
> confrontational or trolling; I honestly don't know the answer and I
> had similar questions when I first started with the 3.0 release
> candidates and I have yet to find a good answer in the Python v3.0
> documentation.  

Yes, it's really the official way. You can google up the discussion
between me and Guido on the python-dev list if you don't trust me. ;)
The docs concur with me, too.

http://docs.python.org/3.0/library/sys.html#sys.stdin

Note: The standard streams are in text mode by default. To write or read
binary data to these, use the underlying binary buffer. For example, to
write bytes to stdout, use sys.stdout.buffer.write(b'abc').

> Why wouldn't you just use:
>
> print(bytes.decode(b'abc\n'), end='')

Because it doesn't work with binary data. You can't convert random bytes
to unicode. Try that with a JPEG file or even the byte sequence that
contains some invalid UTF-8 chars.

>>> bytes((255, 255, 255))
b'\xff\xff\xff'
>>> bytes((255, 255, 255)).decode()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'utf8' codec can't decode byte 0xff in position 0:
unexpected code byte

Christian




More information about the Python-list mailing list