实现如下所示的状态栏:
[========== ] 45%
[================ ] 60%
[==========================] 100%
我想把这个打印到标准输出,并保持刷新,而不是打印到另一行。如何做到这一点?
实现如下所示的状态栏:
[========== ] 45%
[================ ] 60%
[==========================] 100%
我想把这个打印到标准输出,并保持刷新,而不是打印到另一行。如何做到这一点?
当前回答
我发现有用的库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可以包装任何可迭代对象。
其他回答
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/
这是一个简单的0导入进度条形码
#!/usr/bin/python3
def progressbar(current_value,total_value,bar_lengh,progress_char):
percentage = int((current_value/total_value)*100) # Percent Completed Calculation
progress = int((bar_lengh * current_value ) / total_value) # Progress Done Calculation
loadbar = "Progress: [{:{len}}]{}%".format(progress*progress_char,percentage,len = bar_lengh) # Progress Bar String
print(loadbar, end='\r') # Progress Bar Output
if __name__ == "__main__":
the_list = range(1,301)
for i in the_list:
progressbar(i,len(the_list),30,'■')
print("\n")
进度: [■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■■
使用@Mark-Rushakoff的答案,我想出了一个更简单的方法,不需要调用sys库。它适用于Python 3。Windows测试:
from time import sleep
for i in range(21):
# the exact output you're looking for:
print ("\r[%-20s] %d%%" % ('='*i, 5*i), end='')
sleep(0.25)
没有一个答案能完全满足我的需求。所以我写了我自己的,如上所示。我需要的功能:
只传递步数和总步数,它就完成了计算完成百分比的困难工作。 使用60个字符,将它们分成480个“刻度”,每个刻度产生0.21%的收益。如果没有勾号,每个字符只占1.67%。 支持将标题放在前面。 行尾完成百分比可选。 可变长度的进度条,默认为60个字符或480个“刻度”。 设置进度条颜色,默认为绿色。
如何调用进度显示
调用进度显示非常简单。对于上面的样例.gif函数调用使用:
percent_complete(step, total_steps, title="Convert Markdown")
在CSV格式的Stack Exchange Data Dump中,len(rows)的total_steps约为2,500。该步骤是当前行号,因为每个Stack Exchange Markdown问答都转换为Kramdown(用于GitHub页面)。
Python代码
代码很简单,但比其他答案长一些:
def percent_complete(step, total_steps, bar_width=60, title="", print_perc=True):
import sys
# UTF-8 left blocks: 1, 1/8, 1/4, 3/8, 1/2, 5/8, 3/4, 7/8
utf_8s = ["█", "▏", "▎", "▍", "▌", "▋", "▊", "█"]
perc = 100 * float(step) / float(total_steps)
max_ticks = bar_width * 8
num_ticks = int(round(perc / 100 * max_ticks))
full_ticks = num_ticks / 8 # Number of full blocks
part_ticks = num_ticks % 8 # Size of partial block (array index)
disp = bar = "" # Blank out variables
bar += utf_8s[0] * int(full_ticks) # Add full blocks into Progress Bar
# If part_ticks is zero, then no partial block, else append part char
if part_ticks > 0:
bar += utf_8s[part_ticks]
# Pad Progress Bar with fill character
bar += "▒" * int((max_ticks/8 - float(num_ticks)/8.0))
if len(title) > 0:
disp = title + ": " # Optional title to progress display
# Print progress bar in green: https://stackoverflow.com/a/21786287/6929343
disp += "\x1b[0;32m" # Color Green
disp += bar # Progress bar to progress display
disp += "\x1b[0m" # Color Reset
if print_perc:
# If requested, append percentage complete to progress display
if perc > 100.0:
perc = 100.0 # Fix "100.04 %" rounding error
disp += " {:6.2f}".format(perc) + " %"
# Output to terminal repetitively over the same line using '\r'.
sys.stdout.write("\r" + disp)
sys.stdout.flush()
Python代码注释
以下几点:
The [ .... ] bracket placeholders requirement in the question are not necessary because there is the fill characters that serve the same purpose. This saves two extra characters to make the progress bar wider. The bar_width keyword parameter can be used depending on screen width. The default of 60 seems a good fit for most purposes. The print_perc=True keyword parameter default can be overridden by passing print_perc=False when calling the function. This would allow a longer progress bar. The title="" keyword parameter defaults to no title. Should you desire one use title="My Title" and : will automatically be added to it. When your program finishes remember to call sys.stdout.write("\r") followed by sys.stdout.flush() to clear the progress display line.
总结
这个答案比其他答案长一点,但重要的是要注意它是一个完整的解决方案,而不是需要添加更多代码的解决方案的一部分。
另一点是这个解决方案没有依赖关系,也不需要安装任何额外的东西。Python支持UTF-8字符集,不需要额外设置gnome-terminal。如果你使用的是python2.7,在shebang后面可能需要# -*- coding: utf-8 -*-。IE作为程序的第二行。
该函数可以转换为具有单独的init、update、pause(用于将调试内容打印到屏幕上)、resume和close方法的类。
这个函数是从bash脚本转换过来的:
如何将进度条添加到shell脚本?
bash脚本将显示索尼电视音量与libnotify-bin(弹出泡泡消息)每当电视音量改变。如果您对bash进度条感兴趣,请访问Stack Overflow链接。
编辑于2022年1月30日
每个角色从4个刻度改为8个刻度。 移除整块之间的间隙。 添加颜色支持。
只使用内置的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