首页 > 解决方案 > Python sys.stdout.flush() 似乎不起作用

问题描述

我想通过反复覆盖 print 函数来查看我的 for 循环的进度。我希望每次循环进行时都会覆盖打印的行。发生的事情是,在每个循环之后,都会在前一个打印行的正下方打印一个新行。这是通过从打印行中删除 \n 来解决的,因为 \n 会导致每次覆盖一个新的空行,而不是覆盖第一个打印行。

import sys
import time

count1=0
x=10
for i in range(x):
    count1+=1
    sys.stdout.write("\r{} out of {}...\n".format(count1, x))
    sys.stdout.flush()
    time.sleep(.1)

我在 Jupter Notebook 4.3.1 中使用 Python 3.6(64 位)。在 Windows 10 上。

我已经查看了 Stack Overflow 上发布的几个问题,但我还没有能够解决它。

谢谢!

标签: pythonprintingoverwriteflushsys

解决方案


删除创建新行的“\n”。

sys.stdout.write("\r{} out of {}...".format(count1, x))

推荐阅读