Python 从无缓冲的 Stdin 读取和输出
在 C++ 或任何其他语言中,您可以编写连续从 stdin 获取输入行并在每行后输出结果的程序。像这样的事情:
while (true) {
readline
break if eof
print process(line)
}
我似乎无法在Python中得到这种行为,因为它缓冲输出(即在循环退出之前不会发生打印(?))。因此,当程序完成时,所有内容都会被打印出来。如何获得与 C 程序相同的行为(其中 endl 刷新)。
In C++ or any other languages, you can write programs that continuously take input lines from stdin and output the result after each line. Something like:
while (true) {
readline
break if eof
print process(line)
}
I can't seem to get this kind of behavior in Python because it buffers the output (i.e. no printing will happen until the loop exits (?)). Thus, everything is printed when the program finishes. How do I get the same behavior as with C programs (where endl flushes).
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
你有一个可以说明问题的例子吗?
例如(Python 3):
在每行之后打印每行的长度。
Do you have an example which shows the problem?
For example (Python 3):
Prints the length of each line after each line.
使用 sys.stdout.flush() 刷新打印缓冲区。
文档:http://docs.python.org/library/sys.html
use sys.stdout.flush() to flush out the print buffer.
Docs : http://docs.python.org/library/sys.html
Python 不应缓冲换行符之后的文本,但如果发生这种情况,您可以尝试 sys.stdout.flush() 。
Python should not buffer text past newlines, but you could try
sys.stdout.flush()
if that's what is happening.然后我在终端中运行它并在“123”和“456”之后按 Enter
then i run it in terminal and hit Enter after '123' and '456'