终端中带有块字符的文本进度条[关闭]
- 2024-12-12 08:41:00
- admin 原创
- 151
问题描述:
我编写了一个简单的控制台应用程序,使用 ftplib 从 FTP 服务器上传和下载文件。
我希望应用程序能够向用户显示其下载/上传进度的可视化效果;每次下载数据块时,我希望它提供进度更新,即使它只是一个百分比这样的数字表示。
重要的是,我想避免删除前几行打印到控制台的所有文本(即,我不想在打印更新的进度时“清除”整个终端)。
这似乎是一个相当常见的任务——我怎样才能制作一个进度条或类似的可视化效果并输出到我的控制台,同时保留之前的程序输出?
解决方案 1:
Python 3
简单、可定制的进度条
以下是我经常使用的许多答案的汇总(无需导入)。
注意:此答案中的所有代码都是为 Python 3 创建的;请参阅答案末尾以将此代码与 Python 2 一起使用。
# Print iterations progress
def printProgressBar (iteration, total, prefix = '', suffix = '', decimals = 1, length = 100, fill = '█', printEnd = "
"):
"""
Call in a loop to create terminal progress bar
@params:
iteration - Required : current iteration (Int)
total - Required : total iterations (Int)
prefix - Optional : prefix string (Str)
suffix - Optional : suffix string (Str)
decimals - Optional : positive number of decimals in percent complete (Int)
length - Optional : character length of bar (Int)
fill - Optional : bar fill character (Str)
printEnd - Optional : end character (e.g. "
", "
") (Str)
"""
percent = ("{0:." + str(decimals) + "f}").format(100 * (iteration / float(total)))
filledLength = int(length * iteration // total)
bar = fill * filledLength + '-' * (length - filledLength)
print(f'
{prefix} |{bar}| {percent}% {suffix}', end = printEnd)
# Print New Line on Complete
if iteration == total:
print()
示例用法
import time
# A List of Items
items = list(range(0, 57))
l = len(items)
# Initial call to print 0% progress
printProgressBar(0, l, prefix = 'Progress:', suffix = 'Complete', length = 50)
for i, item in enumerate(items):
# Do stuff...
time.sleep(0.1)
# Update Progress Bar
printProgressBar(i + 1, l, prefix = 'Progress:', suffix = 'Complete', length = 50)
示例输出
Progress: |█████████████████████████████████████████████-----| 90.0% Complete
更新
评论中讨论了允许进度条动态调整到终端窗口宽度的选项。虽然我不推荐这样做,但这里有一个实现此功能的要点(并注明了注意事项)。
上述内容的单次调用版本
下面的评论引用了对类似问题的一个很好的回答sys
。我喜欢它所展示的易用性,并写了一个类似的,但选择省略模块的导入,同时添加printProgressBar
上面原始函数的一些功能。
与上面的原始函数相比,这种方法的一些好处包括消除了对在 0% 时打印进度条的函数的初始调用,并且使用enumerate
变得可选(即,不再明确要求使函数工作)。
def progressBar(iterable, prefix = '', suffix = '', decimals = 1, length = 100, fill = '█', printEnd = "
"):
"""
Call in a loop to create terminal progress bar
@params:
iterable - Required : iterable object (Iterable)
prefix - Optional : prefix string (Str)
suffix - Optional : suffix string (Str)
decimals - Optional : positive number of decimals in percent complete (Int)
length - Optional : character length of bar (Int)
fill - Optional : bar fill character (Str)
printEnd - Optional : end character (e.g. "
", "
") (Str)
"""
total = len(iterable)
# Progress Bar Printing Function
def printProgressBar (iteration):
percent = ("{0:." + str(decimals) + "f}").format(100 * (iteration / float(total)))
filledLength = int(length * iteration // total)
bar = fill * filledLength + '-' * (length - filledLength)
print(f'
{prefix} |{bar}| {percent}% {suffix}', end = printEnd)
# Initial Call
printProgressBar(0)
# Update Progress Bar
for i, item in enumerate(iterable):
yield item
printProgressBar(i + 1)
# Print New Line on Complete
print()
示例用法
import time
# A List of Items
items = list(range(0, 57))
# A Nicer, Single-Call Usage
for item in progressBar(items, prefix = 'Progress:', suffix = 'Complete', length = 50):
# Do stuff...
time.sleep(0.1)
示例输出
Progress: |█████████████████████████████████████████████-----| 90.0% Complete
Python 2
要在 Python 2 中使用上述函数,请在脚本顶部将编码设置为 UTF-8:
# -*- coding: utf-8 -*-
并替换此行中的 Python 3 字符串格式:
print(f'
{prefix} |{bar}| {percent}% {suffix}', end = printEnd)
使用 Python 2 字符串格式:
print('
%s |%s| %s%% %s' % (prefix, bar, percent, suffix), end = printEnd)
解决方案 2:
输入‘\r’将使光标移回行首。
显示百分比计数器:
import time
import sys
for i in range(101):
time.sleep(0.05)
sys.stdout.write("
%d%%" % i)
sys.stdout.flush()
解决方案 3:
tqdm:在一秒钟内向您的循环添加进度计:
>>> import time
>>> from tqdm import tqdm
>>> for i in tqdm(range(100)):
... time.sleep(1)
...
|###-------| 35/100 35% [elapsed: 00:35 left: 01:05, 1.00 iters/sec]
解决方案 4:
`
`向控制台写入一个。这是一个“回车符”,它会导致其后的所有文本都回显在行首。例如:
def update_progress(progress):
print '
[{0}] {1}%'.format('#'*(progress/10), progress)
它会给你类似这样的结果:[ ########## ] 100%
解决方案 5:
它少于 10 行代码。
要点在这里:https://gist.github.com/vladignatyev/06860ec2040cb497f0f3
import sys
def progress(count, total, suffix=''):
bar_len = 60
filled_len = int(round(bar_len * count / float(total)))
percents = round(100.0 * count / float(total), 1)
bar = '=' * filled_len + '-' * (bar_len - filled_len)
sys.stdout.write('[%s] %s%s ...%s
' % (bar, percents, '%', suffix))
sys.stdout.flush() # As suggested by Rom Ruben
解决方案 6:
尝试一下Python 的莫扎特 Armin Ronacher 编写的点击库。
$ pip install click # both 2 and 3 compatible
创建一个简单的进度条:
import click
with click.progressbar(range(1000000)) as bar:
for i in bar:
pass
它看起来是这样的:
# [###-------------------------------] 9% 00:01:14
根据您的心意定制:
import click, sys
with click.progressbar(range(100000), file=sys.stderr, show_pos=True, width=70, bar_template='(_(_)=%(bar)sD(_(_| %(info)s', fill_char='=', empty_char=' ') as bar:
for i in bar:
pass
自定义外观:
(_(_)===================================D(_(_| 100000/100000 00:00:02
还有更多选项,请参阅API 文档:
click.progressbar(iterable=None, length=None, label=None, show_eta=True, show_percent=None, show_pos=False, item_show_func=None, fill_char='#', empty_char='-', bar_template='%(label)s [%(bar)s] %(info)s', info_sep=' ', width=36, file=None, color=None)
解决方案 7:
我意识到我来晚了,但是这里有一个我写的略带 Yum 风格(Red Hat)的代码(这里不追求 100% 的准确率,但如果你使用进度条来达到那种程度的准确率,那么你无论如何都是错的):
import sys
def cli_progress_test(end_val, bar_length=20):
for i in xrange(0, end_val):
percent = float(i) / end_val
hashes = '#' * int(round(percent * bar_length))
spaces = ' ' * (bar_length - len(hashes))
sys.stdout.write("
Percent: [{0}] {1}%".format(hashes + spaces, int(round(percent * 100))))
sys.stdout.flush()
应该产生类似这样的结果:
Percent: [############## ] 69%
...其中括号保持不变,只有哈希值增加。
这可能更适合用作装饰器。改天再说吧……
解决方案 8:
检查这个库:clint
它有很多功能,包括进度条:
from time import sleep
from random import random
from clint.textui import progress
if __name__ == '__main__':
for i in progress.bar(range(100)):
sleep(random() * 0.2)
for i in progress.dots(range(100)):
sleep(random() * 0.2)
此链接简要概述了其功能
解决方案 9:
这是一个用 Python 编写的进度条的很好的例子:http ://nadiana.com/animated-terminal-progress-bar-in-python
但如果你想自己写。你可以使用curses
模块让事情变得更容易:)
[编辑] 也许“更简单”这个词并不适合用在 curses 上。但是如果你想要创建一个功能齐全的 cui,curses 可以帮你处理很多事情。
[编辑] 由于旧链接已失效,我已经放上了自己版本的 Python 进度条,可从此处获取:https://github.com/WoLpH/python-progressbar
解决方案 10:
import time,sys
for i in range(100+1):
time.sleep(0.1)
sys.stdout.write(('='*i)+(''*(100-i))+("
[ %d"%i+"% ] "))
sys.stdout.flush()
输出
[ 29% ] ===================
解决方案 11:
安装tqdm
.( pip install tqdm
) 并按如下方式使用:
import time
from tqdm import tqdm
for i in tqdm(range(1000)):
time.sleep(0.01)
这是一个 10 秒的进度条,它将输出如下内容:
47%|██████████████████▊ | 470/1000 [00:04<00:05, 98.61it/s]
解决方案 12:
并且,只是为了添加到堆中,这里有一个你可以使用的对象:
将以下内容添加到新文件progressbar.py
import sys
class ProgressBar(object):
CHAR_ON = '='
CHAR_OFF = ' '
def __init__(self, end=100, length=65):
self._end = end
self._length = length
self._chars = None
self._value = 0
@property
def value(self):
return self._value
@value.setter
def value(self, value):
self._value = max(0, min(value, self._end))
if self._chars != (c := int(self._length * (self._value / self._end))):
self._chars = c
sys.stdout.write("
{:3n}% [{}{}]".format(
int((self._value / self._end) * 100.0),
self.CHAR_ON * int(self._chars),
self.CHAR_OFF * int(self._length - self._chars),
))
sys.stdout.flush()
def __enter__(self):
self.value = 0
return self
def __exit__(self, *args, **kwargs):
sys.stdout.write('
')
可以包含在您的程序中:
import time
from progressbar import ProgressBar
count = 150
print("starting things:")
with ProgressBar(count) as bar:
for i in range(count + 1):
bar.value += 1
time.sleep(0.01)
print("done")
结果:
starting things:
100% [=================================================================]
done
这可能有些“夸张”,但经常使用的话会很方便。
解决方案 13:
在 Python 命令行运行此命令(而不是在任何 IDE 或开发环境中):
>>> import threading
>>> for i in range(50+1):
... threading._sleep(0.5)
... print "
%3d" % i, ('='*i)+('-'*(50-i)),
在我的 Windows 系统上运行良好。
解决方案 14:
尝试安装这个包 pip install progressbar2
::
import time
import progressbar
for i in progressbar.progressbar(range(100)):
time.sleep(0.02)
progressbar github:https://github.com/WoLpH/python-progressbar
解决方案 15:
一个非常简单的解决方案是将此代码放入循环中:
将其放在文件主体(即顶部)中:
import sys
将其放入循环主体中:
sys.stdout.write("-") # prints a dash for each iteration of loop
sys.stdout.flush() # ensures bar is displayed incrementally
解决方案 16:
http://code.activestate.com/recipes/168639-progress-bar-class/(2002)
http://code.activestate.com/recipes/299207-console-text-progress-indicator-class/(2004)
还有大量的教程等待谷歌搜索。
解决方案 17:
根据以上答案以及有关 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 = 10 # 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
"
if progress < 0:
progress = 0
status = "Halt...
"
if progress >= 1:
progress = 1
status = "Done...
"
block = int(round(barLength*progress))
text = "
Percent: [{0}] {1}% {2}".format( "#"*block + "-"*(barLength-block), progress*100, status)
sys.stdout.write(text)
sys.stdout.flush()
看起来像
百分比:[##########] 99.0%
解决方案 18:
我正在使用reddit 的进度。我喜欢它,因为它可以在一行中打印每个项目的进度,并且不会从程序中删除打印输出。
编辑:固定链接
解决方案 19:
我建议使用 tqdm - https://pypi.python.org/pypi/tqdm - 它可以轻松地将任何可迭代或进程转换为进度条,并处理所需的所有终端问题。
摘自文档:“tqdm 可以轻松支持回调/钩子和手动更新。下面是使用 urllib 的示例”
import urllib
from tqdm import tqdm
def my_hook(t):
"""
Wraps tqdm instance. Don't forget to close() or __exit__()
the tqdm instance once you're done with it (easiest using `with` syntax).
Example
-------
>>> with tqdm(...) as t:
... reporthook = my_hook(t)
... urllib.urlretrieve(..., reporthook=reporthook)
"""
last_b = [0]
def inner(b=1, bsize=1, tsize=None):
"""
b : int, optional
Number of blocks just transferred [default: 1].
bsize : int, optional
Size of each block (in tqdm units) [default: 1].
tsize : int, optional
Total size (in tqdm units). If [default: None] remains unchanged.
"""
if tsize is not None:
t.total = tsize
t.update((b - last_b[0]) * bsize)
last_b[0] = b
return inner
eg_link = 'http://www.doc.ic.ac.uk/~cod11/matryoshka.zip'
with tqdm(unit='B', unit_scale=True, miniters=1,
desc=eg_link.split('/')[-1]) as t: # all optional kwargs
urllib.urlretrieve(eg_link, filename='/dev/null',
reporthook=my_hook(t), data=None)
解决方案 20:
import sys
def progresssbar():
for i in range(100):
time.sleep(1)
sys.stdout.write("%i
" % i)
progressbar()
注意:如果您在交互式编译器中运行此程序,您会得到打印出来的额外数字。
解决方案 21:
哈哈,我刚刚为此写了一整套代码,请记住,在执行块 ascii 时不能使用 unicode,我使用 cp437
import os
import time
def load(left_side, right_side, length, time):
x = 0
y = ""
print "
"
while x < length:
space = length - len(y)
space = " " * space
z = left + y + space + right
print "
", z,
y += "█"
time.sleep(time)
x += 1
cls()
你可以这样称呼它
print "loading something awesome"
load("|", "|", 10, .01)
所以看起来像这样
loading something awesome
|█████ |
解决方案 22:
通过上述出色的建议,我制定了进度条。
但我想指出一些缺点
每次刷新进度条时,都会从新行开始
print('
[{0}]{1}%'.format('#' * progress* 10, progress))
像这样:
[] 0%
[#] 10%
[##] 20%
[###] 30%
2.方括号']'和右边的百分号随着'###'的长度而右移。3
.如果表达式'progress / 10'不能返回整数,则会出错。
下面的代码将修复上述问题。
def update_progress(progress, total):
print('
[{0:10}]{1:>2}%'.format('#' * int(progress * 10 /total), progress), end='')
解决方案 23:
对于python 3:
def progress_bar(current_value, total):
increments = 50
percentual = ((current_value/ total) * 100)
i = int(percentual // (100 / increments ))
text = "
[{0: <{1}}] {2}%".format('=' * i, increments, percentual)
print(text, end="
" if percentual == 100 else "")
解决方案 24:
Greenstick 2.7 版的功能:
def printProgressBar (iteration, total, prefix = '', suffix = '',decimals = 1, length = 100, fill = '#'):
percent = ("{0:." + str(decimals) + "f}").format(100 * (iteration / float(total)))
filledLength = int(length * iteration // total)
bar = fill * filledLength + '-' * (length - filledLength)
print'
%s |%s| %s%% %s' % (prefix, bar, percent, suffix),
sys.stdout.flush()
# Print New Line on Complete
if iteration == total:
print()
解决方案 25:
Python 终端进度条的代码
import sys
import time
max_length = 5
at_length = max_length
empty = "-"
used = "%"
bar = empty * max_length
for i in range(0, max_length):
at_length -= 1
#setting empty and full spots
bar = used * i
bar = bar+empty * at_length
#
is carriage return(sets cursor position in terminal to start of line)
# character escape
sys.stdout.write("[{}]
".format(bar))
sys.stdout.flush()
#do your stuff here instead of time.sleep
time.sleep(1)
sys.stdout.write("
")
sys.stdout.flush()
解决方案 26:
Python 模块progressbar是一个不错的选择。这是我的典型代码:
import time
import progressbar
widgets = [
' ', progressbar.Percentage(),
' ', progressbar.SimpleProgress(format='(%(value_s)s of %(max_value_s)s)'),
' ', progressbar.Bar('>', fill='.'),
' ', progressbar.ETA(format_finished='- %(seconds)s -', format='ETA: %(seconds)s', ),
' - ', progressbar.DynamicMessage('loss'),
' - ', progressbar.DynamicMessage('error'),
' '
]
bar = progressbar.ProgressBar(redirect_stdout=True, widgets=widgets)
bar.start(100)
for i in range(100):
time.sleep(0.1)
bar.update(i + 1, loss=i / 100., error=i)
bar.finish()
解决方案 27:
我写了一个简单的进度条:
def bar(total, current, length=10, prefix="", filler="#", space=" ", oncomp="", border="[]", suffix=""):
if len(border) != 2:
print("parameter 'border' must include exactly 2 symbols!")
return None
print(prefix + border[0] + (filler * int(current / total * length) +
(space * (length - int(current / total * length)))) + border[1], suffix, "
", end="")
if total == current:
if oncomp:
print(prefix + border[0] + space * int(((length - len(oncomp)) / 2)) +
oncomp + space * int(((length - len(oncomp)) / 2)) + border[1], suffix)
if not oncomp:
print(prefix + border[0] + (filler * int(current / total * length) +
(space * (length - int(current / total * length)))) + border[1], suffix)
如您所见,它有:条的长度、前缀和后缀、填充符、空格、100% 条内的文本(oncomp)和边框
这里有一个例子:
from time import sleep, time
start_time = time()
for i in range(10):
pref = str((i+1) * 10) + "% "
complete_text = "done in %s sec" % str(round(time() - start_time))
sleep(1)
bar(10, i + 1, length=20, prefix=pref, oncomp=complete_text)
正在进行中:
30% [###### ]
完成:
100% [ done in 9 sec ]
解决方案 28:
整理一下我在这里发现的一些想法,并添加预计剩余时间:
import datetime, sys
start = datetime.datetime.now()
def print_progress_bar (iteration, total):
process_duration_samples = []
average_samples = 5
end = datetime.datetime.now()
process_duration = end - start
if len(process_duration_samples) == 0:
process_duration_samples = [process_duration] * average_samples
process_duration_samples = process_duration_samples[1:average_samples-1] + [process_duration]
average_process_duration = sum(process_duration_samples, datetime.timedelta()) / len(process_duration_samples)
remaining_steps = total - iteration
remaining_time_estimation = remaining_steps * average_process_duration
bars_string = int(float(iteration) / float(total) * 20.)
sys.stdout.write(
"
[%-20s] %d%% (%s/%s) Estimated time left: %s" % (
'='*bars_string, float(iteration) / float(total) * 100,
iteration,
total,
remaining_time_estimation
)
)
sys.stdout.flush()
if iteration + 1 == total:
print
# Sample usage
for i in range(0,300):
print_progress_bar(i, 300)
解决方案 29:
嗯,这是有效的代码,我在发布之前对其进行了测试:
import sys
def prg(prog, fillchar, emptchar):
fillt = 0
emptt = 20
if prog < 100 and prog > 0:
prog2 = prog/5
fillt = fillt + prog2
emptt = emptt - prog2
sys.stdout.write("
[" + str(fillchar)*fillt + str(emptchar)*emptt + "]" + str(prog) + "%")
sys.stdout.flush()
elif prog >= 100:
prog = 100
prog2 = prog/5
fillt = fillt + prog2
emptt = emptt - prog2
sys.stdout.write("
[" + str(fillchar)*fillt + str(emptchar)*emptt + "]" + str(prog) + "%" + "
Done!")
sys.stdout.flush()
elif prog < 0:
prog = 0
prog2 = prog/5
fillt = fillt + prog2
emptt = emptt - prog2
sys.stdout.write("
[" + str(fillchar)*fillt + str(emptchar)*emptt + "]" + str(prog) + "%" + "
Halted!")
sys.stdout.flush()
优点:
20 个字符条(每 5 个字符为 1 个字符(按数字))
自定义填充字符
自定义空字符
停止(任何小于 0 的数字)
完成(100 及 100 以上的任何数字)
进度计数(0-100(以下和以上用于特殊功能))
条形旁边显示百分比数字,且为单行
缺点:
仅支持整数(但可以修改它以支持整数除法,方法是将除法变为整数除法,因此只需更改
prog2 = prog/5
为prog2 = int(prog/5)
)
解决方案 30:
这是我的 Python3 解决方案:
import time
for i in range(100):
time.sleep(1)
s = "{}% Complete".format(i)
print(s,end=len(s) * '')
'\b' 是字符串中每个字符的反斜杠。这在 Windows cmd 窗口中不起作用。