python编写文本进度条
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python编写文本进度条相关的知识,希望对你有一定的参考价值。
参考技术A 方法1:利用 * 打印出文本进度条import time
scale=10
print("---执行开始-----")
for i in range(scale+1):
a='*'*i
b='.'*(scale-i)
c=(i/scale)*100
print(":^8.0f%[->]".format(c,a,b))
time.sleep(0.1)
print("---执行结束-----")
方法2:利用 \u2588 打印出文本进度条
import time
scale=10
print("---执行开始-----")
for i in range(scale+1):
a='\u2588'*i
b='.'*(scale-i)
c=(i/scale)*100
print(":^8.0f%[->]".format(c,a,b))
time.sleep(0.1)
print("---执行结束-----")
方法3:利用 tqdm 打印出文本进度条(首先安装tqdm库 进入命令提示符页面,然后输入,pip install tqdm)
import time
from tqdm import tqdm
for i in tqdm(range(100),desc='progress',ncols=100,ascii=' =',bar_format='l_barbarl'):
time.sleep (0.05)
方法4:利用 progressbar 打印出文本进度条(首先安装progressbar 库 进入命令提示符页面,然后输入,pip install progressbar )
import time
from progressbar import *
progress=ProgressBar()
for i in progress(range(100)):
time.sleep (0.05)
print('')
控制台中的文本进度条[关闭]
有一个很好的方法来做到以下几点?
我写了一个简单的控制台应用程序,使用ftplib从FTP服务器上传和下载文件。
每次下载一些数据块时,我都想更新文本进度条,即使它只是一个数字。
但我不想删除所有打印到控制台的文本。 (执行“清除”然后打印更新的百分比。)
以下是我经常使用的许多答案的汇总。注意:这适用于Python 3;有关在Python 2中使用它的详细信息,请参阅注释。
# Print iterations progress
def printProgressBar (iteration, total, prefix = '', suffix = '', decimals = 1, length = 100, fill = '█'):
"""
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)
"""
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), end = '
')
# Print New Line on Complete
if iteration == total:
print()
样品用法:
from time import sleep
# 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...
sleep(0.1)
# Update Progress Bar
printProgressBar(i + 1, l, prefix = 'Progress:', suffix = 'Complete', length = 50)
样本输出:
Progress: |█████████████████████████████████████████████-----| 90.0% Complete
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% ] ===================
并且,只是为了添加到堆中,这是您可以使用的对象
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("
%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("
")
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
这通常被认为是“超过顶部”,但是当你经常使用它时它很方便
在Python命令行(不在任何IDE或开发环境中)运行此命令:
>>> import threading
>>> for i in range(50+1):
... threading._sleep(0.5)
... print "
%3d" % i, ('='*i)+('-'*(50-i)),
在我的Windows系统上正常工作。
安装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]
- http://code.activestate.com/recipes/168639-progress-bar-class/(2002)
- http://code.activestate.com/recipes/299207-console-text-progress-indicator-class/(2004)
- http://pypi.python.org/pypi/progressbar(2006)
很多教程都在等待用Google搜索。
我正在使用progress from reddit。我喜欢它,因为它可以打印一行中每个项目的进度,并且它不应该从程序中删除打印输出。
编辑:固定链接
基于上述答案和关于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%
我建议使用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以上是关于python编写文本进度条的主要内容,如果未能解决你的问题,请参考以下文章