如何知道stdin是否包含EOF时为空? [英] How to know when stdin is empty if it contains EOF?

查看:104
本文介绍了如何知道stdin是否包含EOF时为空?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

试图在python中创建简单的克隆

In an attempt to create a simple cat clone in python,

sys.stdout.write(sys.stdin.read())

我注意到这失败了可怕的是包含 CTRL + Z <的二进制文件(即 python cat.py<二进制文件>假定副本)< a href = http://zh.wikipedia.org/wiki/Substitute_character rel = nofollow> EOF /降级字符0x1a ,因为这似乎会引起 read()考虑其工作已完成。我不能简单地循环代码来避免这种情况,因为显然在某些时候, 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.


  • 如何知道何时完全重定向到 stdin 的文件,或者

  • 如何正确处理? li>
  • How to know when the file redirected to stdin is fully read, or
  • how to properly handle this?

推荐答案

此答案

if sys.platform == "win32":
    import msvcrt
    msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
    msvcrt.setmode(sys.stdin.fileno(), os.O_BINARY)

这篇关于如何知道stdin是否包含EOF时为空?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆