Python 从无缓冲的 Stdin 读取和输出

发布于 2024-09-30 04:17:47 字数 263 浏览 0 评论 0原文

在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

ゞ花落谁相伴 2024-10-07 04:17:47

你有一个可以说明问题的例子吗?

例如(Python 3):

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

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

Do you have an example which shows the problem?

For example (Python 3):

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

Prints the length of each line after each line.

笑叹一世浮沉 2024-10-07 04:17:47

使用 sys.stdout.flush() 刷新打印缓冲区。

import sys

while True:
    input = raw_input("Provide input to process")
    # process input
    print process(input)
    sys.stdout.flush()

文档:http://docs.python.org/library/sys.html

use sys.stdout.flush() to flush out the print buffer.

import sys

while True:
    input = raw_input("Provide input to process")
    # process input
    print process(input)
    sys.stdout.flush()

Docs : http://docs.python.org/library/sys.html

离去的眼神 2024-10-07 04:17:47

Python 不应缓冲换行符之后的文本,但如果发生这种情况,您可以尝试 sys.stdout.flush() 。

Python should not buffer text past newlines, but you could try sys.stdout.flush() if that's what is happening.

风铃鹿 2024-10-07 04:17:47
$ cat test.py
import sys

while True:
    print sys.stdin.read(1)

然后我在终端中运行它并在“123”和“456”之后按 Enter

$ python test.py 
123
1
2
3


456
4
5
6
$ cat test.py
import sys

while True:
    print sys.stdin.read(1)

then i run it in terminal and hit Enter after '123' and '456'

$ python test.py 
123
1
2
3


456
4
5
6
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文