![]() |
| 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: 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(). |