我编写了一个简单的控制台应用程序,使用ftplib从FTP服务器上载和下载文件。
我希望该应用程序向用户展示其下载/上传进度的一些可视化;每次下载数据块时,我都希望它提供进度更新,即使它只是数字表示形式(如百分比)。
重要的是,我要避免擦除前一行中已打印到控制台的所有文本(即,我不想在打印更新的进度时“清除”整个终端)。
这似乎是一项相当普通的任务-如何在保留先前程序输出的同时,制作进度条或类似的可视化内容输出到控制台?
我编写了一个简单的控制台应用程序,使用ftplib从FTP服务器上载和下载文件。
我希望该应用程序向用户展示其下载/上传进度的一些可视化;每次下载数据块时,我都希望它提供进度更新,即使它只是数字表示形式(如百分比)。
重要的是,我要避免擦除前一行中已打印到控制台的所有文本(即,我不想在打印更新的进度时“清除”整个终端)。
这似乎是一项相当普通的任务-如何在保留先前程序输出的同时,制作进度条或类似的可视化内容输出到控制台?
Answers:
以下是我经常使用的许多答案的汇总(不需要导入)。
# Print iterations progress
def printProgressBar (iteration, total, prefix = '', suffix = '', decimals = 1, length = 100, fill = '█', printEnd = "\r"):
"""
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. "\r", "\r\n") (Str)
"""
percent = ("{0:." + str(decimals) + "f}").format(100 * (iteration / float(total)))
filledLength = int(length * iteration // total)
bar = fill * filledLength + '-' * (length - filledLength)
print('\r%s |%s| %s%% %s' % (prefix, bar, percent, suffix), end = printEnd)
# Print New Line on Complete
if iteration == total:
print()
注意:这是针对Python 3的;有关在Python 2中使用此功能的详细信息,请参见注释。
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
注释中讨论了一个选项,该选项允许进度条动态调整为终端窗口宽度。虽然我不建议这样做,但是这里有一个实现此功能的要点(并注意了一些警告)。
# Size of terminal rows, columns = [int(x) for x in os.popen('stty size', 'r').read().split()]
columns
应该将终端大小的检测对于此功能有用,应该将其传递给长度,以将进度条的大小调整到终端窗口。尽管应减少bar的进度部分的长度(按此字符串中的前缀,后缀,百分比和其他字符的长度'\r%s |%s| %s%% %s'
end = '\r'
为end = ''
。
写入“ \ r”会将光标移回该行的开头。
这将显示一个百分比计数器:
import time
import sys
for i in range(100):
time.sleep(1)
sys.stdout.write("\r%d%%" % i)
sys.stdout.flush()
99%
将a写入\r
控制台。这是一个“回车符”,它导致其后的所有文本在行的开头被回显。就像是:
def update_progress(progress):
print '\r[{0}] {1}%'.format('#'*(progress/10), progress)
这会给你类似的东西: [ ########## ] 100%
\r
,然后再次将整行写出。基本上:print("\rProgress: [{0:50s}] {1:.1f}%".format('#' * int(amtDone * 50), amtDone * 100))
,其中,amtDone
是在0和1之间的浮动
sys.stdout.write
比更好的使用print
。随着print
我换行。
,
在print
我的作品末尾添加一个逗号。
print("\rProgress: [{0:50s}] {1:.1f}%".format('#' * int(workdone * 50), workdone*100), end="", flush=True)
,其中workdone
的浮点数介于0和1之间,例如workdone = parsed_dirs/total_dirs
它少于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\r' % (bar, percents, '%', suffix))
sys.stdout.flush() # As suggested by Rom Ruben
尝试由Python的Mozart,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)
我意识到我已经迟到了,但是这是我写的一个有点百胜风格(红帽)的东西(这里并不是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("\rPercent: [{0}] {1}%".format(hashes + spaces, int(round(percent * 100))))
sys.stdout.flush()
应该产生如下内容:
Percent: [############## ] 69%
...括号保持固定,仅散列增加。
作为装饰者,这可能会更好。再过一天
这是一个用Python编写的进度条的好例子:http : //nadiana.com/animated-terminal-progress-bar-in-python
但是,如果您想自己编写。您可以使用该curses
模块使事情变得容易:)
也许不是诅咒这个词更容易。但是,如果您想创建一个成熟的cui,那么curses会为您处理很多事情。
[edit]由于旧的链接已失效,因此我设置了自己的Python Progressbar版本,请在此处获取:https : //github.com/WoLpH/python-progressbar
curses
?更轻松?嗯....
并且,只是添加到堆中,这是您可以使用的对象
import sys
class ProgressBar(object):
DEFAULT_BAR_LENGTH = 65
DEFAULT_CHAR_ON = '='
DEFAULT_CHAR_OFF = ' '
def __init__(self, end, start=0):
self.end = end
self.start = start
self._barLength = self.__class__.DEFAULT_BAR_LENGTH
self.setLevel(self.start)
self._plotted = False
def setLevel(self, level):
self._level = level
if level < self.start: self._level = self.start
if level > self.end: self._level = self.end
self._ratio = float(self._level - self.start) / float(self.end - self.start)
self._levelChars = int(self._ratio * self._barLength)
def plotProgress(self):
sys.stdout.write("\r %3i%% [%s%s]" %(
int(self._ratio * 100.0),
self.__class__.DEFAULT_CHAR_ON * int(self._levelChars),
self.__class__.DEFAULT_CHAR_OFF * int(self._barLength - self._levelChars),
))
sys.stdout.flush()
self._plotted = True
def setAndPlot(self, level):
oldChars = self._levelChars
self.setLevel(level)
if (not self._plotted) or (oldChars != self._levelChars):
self.plotProgress()
def __add__(self, other):
assert type(other) in [float, int], "can only add a number"
self.setAndPlot(self._level + other)
return self
def __sub__(self, other):
return self.__add__(-other)
def __iadd__(self, other):
return self.__add__(other)
def __isub__(self, other):
return self.__add__(-other)
def __del__(self):
sys.stdout.write("\n")
if __name__ == "__main__":
import time
count = 150
print "starting things:"
pb = ProgressBar(count)
#pb.plotProgress()
for i in range(0, count):
pb += 1
#pb.setAndPlot(i + 1)
time.sleep(0.01)
del pb
print "done"
结果是:
starting things:
100% [=================================================================]
done
这通常被认为是“顶上的”,但是当您经常使用它时非常方便
我正在使用reddit的进度。我喜欢它,因为它可以在一行中为每个项目打印进度,并且不应该从程序中删除打印输出。
编辑:固定链接
尝试安装此软件包 pip install progressbar2
:
import time
import progressbar
for i in progressbar.progressbar(range(100)):
time.sleep(0.02)
进度条github:https : //github.com/WoLpH/python-progressbar
根据上述答案以及有关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\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%
我建议使用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)
一个非常简单的解决方案是将以下代码放入循环中:
将其放在文件的正文(即顶部)中:
import sys
把它放在循环体中:
sys.stdout.write("-") # prints a dash for each iteration of loop
sys.stdout.flush() # ensures bar is displayed incrementally
import sys
def progresssbar():
for i in range(100):
time.sleep(1)
sys.stdout.write("%i\r" % i)
progressbar()
注意:如果您在互动式拦截器中运行此命令,则会打印出额外的数字
大声笑我只是为此写了很多东西,代码要记住,在执行块ascii时不能使用unicode,我使用cp437
import os
import time
def load(left_side, right_side, length, time):
x = 0
y = ""
print "\r"
while x < length:
space = length - len(y)
space = " " * space
z = left + y + space + right
print "\r", z,
y += "█"
time.sleep(time)
x += 1
cls()
你这样称呼它
print "loading something awesome"
load("|", "|", 10, .01)
所以看起来像这样
loading something awesome
|█████ |
有了以上出色的建议,我就会得出进度条。
但是我想指出一些缺点
每次刷新进度条时,它将在新行开始
print('\r[{0}]{1}%'.format('#' * progress* 10, progress))
像这样:
[] 0%
[#] 10%
[##] 20%
[###] 30%
2.当“ ###”变长时,方括号“]”和右侧的百分数右移。
3.如果表达式“ progress / 10”不能返回整数,则会发生错误。
并且以下代码将解决上述问题。
def update_progress(progress, total):
print('\r[{0:10}]{1:>2}%'.format('#' * int(progress * 10 /total), progress), end='')
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
#\r is carriage return(sets cursor position in terminal to start of line)
#\0 character escape
sys.stdout.write("[{}]\0\r".format(bar))
sys.stdout.flush()
#do your stuff here instead of time.sleep
time.sleep(1)
sys.stdout.write("\n")
sys.stdout.flush()
我写了一个简单的进度栏:
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, "\r", 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 ]
整理一下我在这里找到的一些想法,并增加估计的剩余时间:
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(
"\r[%-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)
对于python 3:
def progress_bar(current_value, total):
increments = 50
percentual = ((current_value/ total) * 100)
i = int(percentual // (100 / increments ))
text = "\r[{0: <{1}}] {2}%".format('=' * i, increments, percentual)
print(text, end="\n" if percentual == 100 else "")
好了,这里的代码行得通,我在发布之前对其进行了测试:
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("\r[" + 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("\r[" + str(fillchar)*fillt + str(emptchar)*emptt + "]" + str(prog) + "%" + "\nDone!")
sys.stdout.flush()
elif prog < 0:
prog = 0
prog2 = prog/5
fillt = fillt + prog2
emptt = emptt - prog2
sys.stdout.write("\r[" + str(fillchar)*fillt + str(emptchar)*emptt + "]" + str(prog) + "%" + "\nHalted!")
sys.stdout.flush()
优点:
缺点:
prog2 = prog/5
为即可prog2 = int(prog/5)
)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'\r%s |%s| %s%% %s' % (prefix, bar, percent, suffix),
sys.stdout.flush()
# Print New Line on Complete
if iteration == total:
print()
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()