Aug-27-2019, 02:17 AM
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:
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?
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?
Tradition is peer pressure from dead people
What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.