如果标准输入包含 EOF,如何知道它何时为空?

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

尝试在 python、

中创建一个简单的 cat 克隆
sys.stdout.write(sys.stdin.read())

我注意到对于包含 CTRL+Z [=16 的二进制文件(即 python cat.py < binaryfile > supposed_copy),这非常失败=],因为这似乎导致 read() 认为其工作已完成。我不能简单地永远循环代码来规避这个问题,因为显然在某些时候 stdin.read() 会等到提供新的输入,一旦到达真正的输入结束就不会发生。

那么,如何解决这个问题,即

您需要告诉 Python 以二进制模式打开 stdinstdout。您可以使用 -u 选项执行此操作。例如

python -u cat.py < binaryfile > supposed_copy

请注意,这将使 stdinstdout 无缓冲。

有关如何确保 stdin/stdout 以二进制文件打开的说明,请参阅 Reading binary data from stdin

this answer 上扩展:

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