问题
In an attempt to create a simple cat
clone in python,
sys.stdout.write(sys.stdin.read())
I noticed that this fails horribly for binary files (i.e. python cat.py < binaryfile > supposed_copy
) containing the CTRL+Z EOF / substitude character 0x1a, since that seems to cause read()
to consider its work done. I cannot simply loop over the code forever to circumvent this, since obviously at some point stdin.read()
will wait until new input is provided, which once the true end of input is reached won't ever happen.
So, how can this be fixed, i.e.
- How to know when the file redirected to
stdin
is fully read, or - how to properly handle this?
回答1:
You will need to tell Python to open stdin
and stdout
in binary mode. You can do this with the -u
option. Eg
python -u cat.py < binaryfile > supposed_copy
Note that this will make stdin
and stdout
unbuffered.
回答2:
Expanding on this answer:
if sys.platform == "win32":
import msvcrt
msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
msvcrt.setmode(sys.stdin.fileno(), os.O_BINARY)
回答3:
See Reading binary data from stdin for an explanation of how to make sure stdin/stdout are opened as binary.
来源:https://stackoverflow.com/questions/28672607/how-to-know-when-stdin-is-empty-if-it-contains-eof