在 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/