How to know when stdin is empty if it contains EOF?

柔情痞子 提交于 2019-12-11 03:13:25

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!