[英]Progress Bar Python
I've got the following piece of code: 我有以下代码:
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)
And for calling the progress bar: 并调用进度条:
total = 100
i = 0
while i < total:
i += 1
progressbar(i, total, status="Creating stuff")
time.sleep(1)
Where total is a number of iterations. 其中total是许多迭代。 When I run this code I get the progress bar running on multiple lines instead of just one.
当我运行此代码时,我得到的进度条是多行而不是多行。 Any advice?
有什么建议吗?
I don't think you have any issue in your code. 我认为您的代码中没有任何问题。
print("[{}] {}{} ...{}".format(bar, percents, "%", status),
**end="\r"**, flush=True)
the end="\\n" argument in print() method should print the progress bar i one line. print()方法中的end =“ \\ n”参数应将进度条打印一行。
if you run this code in terminal it should work fine. 如果您在终端中运行此代码,它应该可以正常工作。
I have previously seen an issue with PyCharm IDE where end="\\r" doesn't work. 我以前见过PyCharm IDE的一个问题,其中end =“ \\ r”不起作用。 It is probably a bug in the terminal emulator in the IDE.
这可能是IDE中的终端仿真器中的错误。
Thanks for everyone that commented on my topic trying to help. 感谢所有对我的主题发表评论并试图提供帮助的人。 I got the solution on another StackOverflow Question: Python 3 progress bar shows nothing
我在另一个StackOverflow上得到了解决方案问题: Python 3进度条什么也没显示
So I tested two ways that were successful. 因此,我测试了两种成功的方法。 The first one, to print using sys.stdout:
第一个,使用sys.stdout打印:
sys.stdout.write("\r[{}] {}{} ...{}".format(bar, percents, "%", status))
sys.stdout.flush()
And the second, using the print() but with the \\r in front of the line: 第二个,使用print(),但在行的前面加上\\ r:
print("\r[{}] {}{} ...{}".format(bar, percents, "%", status),
end="", flush=True)
Both works perfectly. 两者都完美地工作。 The first one needs the import sys.
第一个需要导入系统。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.