3 ms·
So, to make the script work similarly for python3: $ diff test.py test3.py 5c5 < f = sys.stdin --- > f = sys.stdin.buffer 13c1
by e12e 13y ago
So, to make the script work similarly for python3:
$ diff test.py test3.py
5c5
< f = sys.stdin
---
> f = sys.stdin.buffer
13c13
< shutil.copyfileobj(f, sys.stdout)
---
> shutil.copyfileobj(f, sys.stdout.buffer)
We can now read in binary, and write to stdout in binary, and this
script will happily garble your terminal if you point it at /bin/ls. If
the lines above were unclear, here is the entire "python3" version. Note
that we now explicitly treat standard input and output as binary (which is
"wrong"):
import sys
import shutil
for filename in sys.argv[1:]:
f = sys.stdin.buffer
if filename != '-':
try:
f = open(filename, 'rb')
except IOError as err:
print >> sys.stderr, 'cat.py: %s: %s' % (filename, err)
continue
with f:
shutil.copyfileobj(f, sys.stdout.buffer)
And we can now, for example:
$ head -c 200 /bin/ls | python3 test3.py -
ELF>�H@@p�@8 @@@@@@�88@8@@ $
The crucial difference is, that if we wanted only to deal with text,
we'd get a sane error (see above) from python3. I'd probably add a
comment about the sys.stdin.buffer as it isn't exactly obvious that what
we do is go from stdin that is a text stream to the underlying buffer
that is binary -- but I can't really agree that this is super-hard -- it
took me a few minutes to google "python3 binary io" and find this…
And all these scripts (appear to) deal fine with utf-8 file names both
in python2 and 3.
[edit: Having redone this by hand, I see that this is sort of what the "new" script in the post does, with some caveats on how stdin/out is "sometimes" not not binary... I still have a hard time accepting that this short python3 script is much more fragile than the original short python2 script. The fact that you get an error if you try to copy a binary stream to a text stream seems sane to me...]