Search code examples
pythonpython-3.xprintingbytesio

"a bytes-like object is required" but I am using bytes


With Python3 I have re-opened stdout in binary mode. After that when I print("Hello") it tells me that I need to use a bytes-like object. Fair enough, it's in binary mode now.

However when I do this:

print(b"Some bytes")

I still get this error:

TypeError: a bytes-like object is required, not 'str'

What's up with that?


Solution

  • print() always writes str values. It'll convert any arguments to strings first, including bytes objects.

    From the print() documentation:

    All non-keyword arguments are converted to strings like str() does and written to the stream, separated by sep and followed by end.

    You can't use print() on a binary stream, period. Either write directly to the stream (using it's .write() method), or wrap the stream in a TextIOWrapper() object to handle encoding.

    These both work:

    import sys
    
    sys.stdout.write(b'Some bytes\n')  # note, manual newline added
    

    and

    from io import TextIOWrapper
    import sys
    
    print('Some text', file=TextIOWrapper(sys.stdout, encoding='utf8'))