【问题标题】:How to refresh an stdout in python如何在python中刷新标准输出
【发布时间】:2022-01-25 06:23:19
【问题描述】:

您好,提前感谢您的帮助, 事实上,我有一个带有各种选项的进度条,我希望看到这些选项被刷新,而不是花时间清理控制台。

while True :
    #system("cls")
    sys.stdout.write("\rSearching for {} --- [Currently {} found] \nLoading [".format(entry, count_result) + "="*int(100 * count / nb_files) + " "*(100-int(100 * count / nb_files)) + "] {}%".format(int(round(float(int(100 * count / nb_files))))) + "\n")
    sys.stdout.flush()
    sleep(0.5)
    if int(100 * count / nb_files) == 100 :
        sleep(1)
        system("cls")
        break

所以我很想知道是否有办法,我到处寻找以试图理解,但我不明白在我的情况下我该怎么做。提前致谢

【问题讨论】:

  • 使用这个 --> github.com/tqdm/tqdm 而不是试图建立一个进度条
  • 谢谢,但我不想使用外部库。我想了解它是如何工作的并用这种风格来做

标签: python python-3.x printing stdout sys


【解决方案1】:

“刷新”进度条的最简单方法是打印没有LF (\n) 新符号的行。相反,您只需 CR (\r) 回车符号。使用这种方法,光标将返回同一行并重写它

import sys
import time

for i in range(100):
    print("Progress: {}% ".format(i), end="\r")
    time.sleep(.1)

这种方法的主要缺点是它会留下前一行的符号。你可以通过这个例子看到它。

import sys
import time

for i in range(100):
    print("Progress: {}% ".format(i), end="\r")
    time.sleep(.5)
    print("short line", end="\r")
    time.sleep(.5)

所以,你也应该在写一个新的之前清理行

import sys
import time

for i in range(100):    
    print("                                                                     ", end="\r")
    print("Progress: {}% ".format(i), end="\r")
    time.sleep(.1)

这里有更多关于 CR 和 LF 符号的信息What are carriage return, linefeed, and form feed?

【讨论】:

  • 问题是,如果我在 2 行上执行此方法:它们将被删除并交替出现。你不能同时得到它们吗?
  • 好的,我找到了答案 (stackoverflow.com/questions/39455022/…) !再次感谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-12
  • 1970-01-01
  • 1970-01-01
  • 2017-10-26
  • 2013-11-04
相关资源
最近更新 更多