[英]Progress Bar 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是許多迭代。 當我運行此代碼時,我得到的進度條是多行而不是多行。 有什么建議嗎?
我認為您的代碼中沒有任何問題。
print("[{}] {}{} ...{}".format(bar, percents, "%", status),
**end="\r"**, flush=True)
print()方法中的end =“ \\ n”參數應將進度條打印一行。
如果您在終端中運行此代碼,它應該可以正常工作。
我以前見過PyCharm IDE的一個問題,其中end =“ \\ r”不起作用。 這可能是IDE中的終端仿真器中的錯誤。
感謝所有對我的主題發表評論並試圖提供幫助的人。 我在另一個StackOverflow上得到了解決方案問題: Python 3進度條什么也沒顯示
因此,我測試了兩種成功的方法。 第一個,使用sys.stdout打印:
sys.stdout.write("\r[{}] {}{} ...{}".format(bar, percents, "%", status))
sys.stdout.flush()
第二個,使用print(),但在行的前面加上\\ r:
print("\r[{}] {}{} ...{}".format(bar, percents, "%", status),
end="", flush=True)
兩者都完美地工作。 第一個需要導入系統。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.