在Python中,为什么没有换行就不能打印?

Pro*_*404 13 python posix

import time
import sys
sys.stdout.write("1")
time.sleep(5)
print("2")
Run Code Online (Sandbox Code Playgroud)

将在5秒后打印"12"

import time
import sys
sys.stdout.write("1\n")
time.sleep(5)
print("2")
Run Code Online (Sandbox Code Playgroud)

将立即打印"1 \n",然后在5秒后打印"2"

为什么是这样?

tmg*_*tmg 22

如果添加"\n",则会自动刷新流,并且最后不会没有新行.您可以使用以下方式刷新输

sys.stdout.flush()
Run Code Online (Sandbox Code Playgroud)


mar*_*eau 7

因为stdout是缓冲的.您可以通过sys.stdout.flush()呼叫尽快强制输出.


Mat*_*bel 5

sys 模块中的 sys.stdout.write 命令有意打印出不带 \n 字符的语句。这就是对 stdout 流的正常调用的工作方式,例如在 C++ 或 C 中,其中必须手动添加 \n 字符。

然而,Python 提供的 print 命令会自动在字符串中添加一个 \n 字符,从而简化了代码并使其更易于阅读。

出现第一个结果中的现象的原因是系统正在等待由 \n 字符提供的刷新打印输出。您可以使用此命令来避免这种情况,sys.stdout.flush()该命令将刷新标准输出流,强制其打印。