执行 print("Enter text: ", end="") sys.stdin.readline() 在 Python-3 中无法正常工作

Doing print("Enter text: ", end="") sys.stdin.readline() does not work properly in Python-3

我这样做的时候发生了一些奇怪的事情

import sys

print("Enter text: ", end="")
sys.stdin.readline()

输出:

<input>
Enter text: 

(这里,<input>(不包括引号表示输入发生在该行))

为什么代码 运行 好像我的代码是

import sys

sys.stdin.readline()
print("Enter text: ", end="")

(Debian/Ubuntu, Python-3.8.10)

有什么原因吗?

我想,stdout 在您输入之前还没有刷新。

试试这个

import sys

print("Enter text: ", end="")
sys.stdout.flush()
sys.stdin.readline()
> Enter text: 123

什么时候刷新

这个answer解释了刷新的原因为newline:

Normally output to a file or the console is buffered, with text output at least until you print a newline. The flush makes sure that any output that is buffered goes to the destination.

为什么这个打印不冲洗

在您的语句 print("Enter text: ", end="") 中,您既没有强制刷新,也没有打印换行符 - 相反 end 参数被覆盖(默认为 \n 换行符)。因此,指定的文本仅打印到缓冲区,尚未刷新到控制台。

如何强制刷新

内置函数print()有一个名为flush的参数,默认为False:

print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)

[..] Whether the output is buffered is usually determined by file, but if the flush keyword argument is true, the stream is forcibly flushed.

另见

  • How can I flush the output of the print function (unbuffer python output)?
  • How to overwrite the previous print to stdout in python?
  • What does print()'s `flush` do?
  • Delft Stack:Flush Print Output in Python,教程