Python Forum
bytes not being printed as expected - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: bytes not being printed as expected (/thread-20719.html)



bytes not being printed as expected - Skaperen - Aug-27-2019

i ran into an issue printing a byte string to a file object opened in binary mode and minimized it to this little 4 line script that runs into the same problem:
Output:
lt2a/forums /home/forums 1> cat -n write_bytes.py 1 #!/usr/bin/env python3 2 from sys import stdout 3 foo = open(stdout.fileno(),'wb') 4 print(b'abcdef xyz foobar',file=foo) lt2a/forums /home/forums 2> cat write_bytes.py #!/usr/bin/env python3 from sys import stdout foo = open(stdout.fileno(),'wb') print(b'abcdef xyz foobar',file=foo) lt2a/forums /home/forums 3> python3 write_bytes.py Traceback (most recent call last): File "write_bytes.py", line 4, in <module> print(b'abcdef xyz foobar',file=foo) TypeError: a bytes-like object is required, not 'str' lt2a/forums /home/forums 4>
can someone explain what is going wrong here?

the source of the issue is a program that is reading from a pipe created by subprocess.Popen() which gets bytes because it opened the pipe in binary. rather than decoding those bytes for every line i was copying, i just re-opened stdout in binary, as this example shows. but it seems to be confused when i print bytes. is print() decoding them back to strings?


RE: bytes not being printed as expected - stranac - Aug-27-2019

Right, you can't use print with binary files. This is mentioned in the docs:
Quote:Since printed arguments are converted to text strings, print() cannot be used with binary mode file objects. For these, use file.write(...) instead.

So just use sys.stdout.buffer.write() and you'll be fine.
I never really understood the point of using print() with a file anyway...


RE: bytes not being printed as expected - Skaperen - Aug-27-2019

i was just trying to copy, to stdout, what a child process printed to its stdout, piped to the parent. ok, so read() and write().


This forum uses Lukasz Tkacz MyBB addons.
Forum use Krzysztof "Supryk" Supryczynski addons.