实现如下所示的状态栏:
[========== ] 45%
[================ ] 60%
[==========================] 100%
我想把这个打印到标准输出,并保持刷新,而不是打印到另一行。如何做到这一点?
实现如下所示的状态栏:
[========== ] 45%
[================ ] 60%
[==========================] 100%
我想把这个打印到标准输出,并保持刷新,而不是打印到另一行。如何做到这一点?
当前回答
根据上面的答案和其他类似的关于CLI进度条的问题,我想我得到了一个普遍的答案。请登录https://stackoverflow.com/a/15860757/2254146查看。
下面是这个函数的一个副本,但是为了适合你的风格进行了修改:
import time, sys
# update_progress() : Displays or updates a console progress bar
## Accepts a float between 0 and 1. Any int will be converted to a float.
## A value under 0 represents a 'halt'.
## A value at 1 or bigger represents 100%
def update_progress(progress):
barLength = 20 # Modify this to change the length of the progress bar
status = ""
if isinstance(progress, int):
progress = float(progress)
if not isinstance(progress, float):
progress = 0
status = "error: progress var must be float\r\n"
if progress < 0:
progress = 0
status = "Halt...\r\n"
if progress >= 1:
progress = 1
status = "Done...\r\n"
block = int(round(barLength*progress))
text = "\rPercent: [{0}] {1}% {2}".format( "="*block + " "*(barLength-block), progress*100, status)
sys.stdout.write(text)
sys.stdout.flush()
看起来像
百分比:[====================]99.0%
其他回答
只使用内置的sys:
import sys
def print_progress_bar(index, total, label):
n_bar = 50 # Progress bar width
progress = index / total
sys.stdout.write('\r')
sys.stdout.write(f"[{'=' * int(n_bar * progress):{n_bar}s}] {int(100 * progress)}% {label}")
sys.stdout.flush()
用法:
foo_list = ["a", "b", "c", "d"]
total = len(foo_list)
for index, item in enumerate(foo_list):
print_progress_bar(index, total, "foo bar")
sleep(0.5)
Enumerate (foo_list)使您可以在循环期间访问索引值。
输出:
[================================================ ] 96% foo bar
对于Python 3.6,以下工作为我更新输出内联:
for current_epoch in range(10):
for current_step) in range(100):
print("Train epoch %s: Step %s" % (current_epoch, current_step), end="\r")
print()
'\r'字符(回车)将光标重置到行首,并允许您重写该行之前的内容。
from time import sleep
import sys
for i in range(21):
sys.stdout.write('\r')
# the exact output you're looking for:
sys.stdout.write("[%-20s] %d%%" % ('='*i, 5*i))
sys.stdout.flush()
sleep(0.25)
我不能100%确定这是否可以在所有系统上完全移植,但它至少可以在Linux和OSX上运行。
PyProg试试。PyProg是Python的一个开源库,用于创建超级可定制的进度指示器和进度条。
它目前的版本是1.0.2;它托管在Github上,在PyPI上可用(链接如下)。它与Python 3和2兼容,也可以与Qt控制台一起使用。
它真的很容易使用。以下代码:
import pyprog
from time import sleep
# Create Object
prog = pyprog.ProgressBar(" ", " ", total=34, bar_length=26, complete_symbol="=", not_complete_symbol=" ", wrap_bar_prefix=" [", wrap_bar_suffix="] ", progress_explain="", progress_loc=pyprog.ProgressBar.PROGRESS_LOC_END)
# Update Progress Bar
prog.update()
for i in range(34):
# Do something
sleep(0.1)
# Set current status
prog.set_stat(i + 1)
# Update Progress Bar again
prog.update()
# Make the Progress Bar final
prog.end()
将产生你想要的(甚至是条长度!):
[=========== ] 45%
[=============== ] 60%
[==========================] 100%
要了解更多自定义进度条的选项,请访问本网站的Github页面。
我实际上做了PyProg,因为我需要一个简单但超级可定制的进度条库。您可以轻松地使用:pip install pyprog安装它。
PyProg Github: https://github.com/Bill13579/pyprog 皮皮:https://pypi.python.org/pypi/pyprog/
我发现有用的库tqdm (https://github.com/tqdm/tqdm/,以前是:https://github.com/noamraph/tqdm)。它可以自动估计完成时间,也可以用作迭代器。
用法:
import tqdm
import time
for i in tqdm.tqdm(range(1000)):
time.sleep(0.01)
# or other long operations
结果:
|####------| 450/1000 45% [elapsed: 00:04 left: 00:05, 99.15 iters/sec]
TQDM可以包装任何可迭代对象。