首页 > 解决方案 > 进度条 Python

问题描述

我有以下代码:

def progressbar(count, total, status=""):
    bar_len = 40
    filled_len = int(round(bar_len * count / float(total)))

    percents = round(100.1 * count / float(total), 1)
    bar = "X" * filled_len + "-" * (bar_len - filled_len)

    print("[{}] {}{} ...{}".format(bar, percents, "%", status),
          end="\r", flush=True)

并调用进度条:

total = 100
i = 0
while i < total:
    i += 1
    progressbar(i, total, status="Creating stuff")
    time.sleep(1)

其中 total 是迭代次数。当我运行此代码时,我会在多行而不是仅一行上运行进度条。有什么建议吗?

标签: pythonprogress-bar

解决方案


我认为您的代码没有任何问题。

print("[{}] {}{} ...{}".format(bar, percents, "%", status),
          **end="\r"**, flush=True)

print() 方法中的 end="\n" 参数应将进度条打印一行。

如果您在终端中运行此代码,它应该可以正常工作。

我之前看到过一个 PyCharm IDE 的问题,其中 end="\r" 不起作用。这可能是 IDE 中终端仿真器中的错误。


推荐阅读