gpt4 book ai didi

Python 从 Stdin Unbuffered 读取和输出

转载 作者:太空宇宙 更新时间:2023-11-03 14:34:29 26 4
gpt4 key购买 nike

在 C++ 或任何其他语言中,您可以编写连续从标准输入获取输入行并在每一行后输出结果的程序。像这样的东西:

while (true) {
readline
break if eof

print process(line)
}

我似乎无法在 Python 中获得这种行为,因为它缓冲了输出(即在循环退出之前不会发生打印(?))。因此,程序结束时打印所有内容。如何获得与 C 程序相同的行为(其中 endl 刷新)。

最佳答案

您有说明问题的示例吗?

例如(Python 3):

def process(line):
return len(line)
try:
while True:
line = input()
print(process(line))
except EOFError:
pass

在每行之后打印每行的长度。

关于Python 从 Stdin Unbuffered 读取和输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4064401/

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