gpt4 book ai didi

python - 在 block 中迭代标准,直到读取 EOF

转载 作者:行者123 更新时间:2023-11-28 17:34:43 24 4
gpt4 key购买 nike

我有两个通过 Unix 管道连接的脚本。第一个脚本将字符串写入标准输出,这些由第二个脚本使用。

考虑以下内容

# producer.py
import sys
import time
for x in range(10):
sys.stdout.write("thing number %d\n"%x)
sys.stdout.flush()
time.sleep(1)

# consumer.py
import sys
for line in sys.stdin:
print line

现在,当我运行:python producer.py | python consumer.py,我希望每秒都能看到一行新的输出。相反,我等了 10 秒钟,然后我突然看到了所有的输出。

为什么我不能一次迭代一个项目的 stdin?为什么我必须等到 producer 在循环体开始执行之前给我一个 EOF

请注意,如果我将 consumer.py 更改为:

,我可以获得正确的行为:
# consumer.py
import sys
def stream_stdin():
line = sys.stdin.readline()
while line:
yield line
line = sys.stdin.readline()

for line in stream_stdin():
print line

我想知道为什么我必须显式构建一个生成器来流式传输 stdin 的项目。为什么这不会隐式发生?

最佳答案

根据python -h帮助信息:

-u Force stdin, stdout and stderr to be totally unbuffered. On systems where it matters, also put stdin, stdout and stderr in binary mode. Note that there is internal buffering in xread‐ lines(), readlines() and file-object iterators ("for line in sys.stdin") which is not influenced by this option. To work around this, you will want to use "sys.stdin.readline()" inside a "while 1:" loop.

关于python - 在 block 中迭代标准,直到读取 EOF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31696444/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com