Панель выполнения текста в консоли
Есть ли хороший способ сделать следующее?
Я написал простое консольное приложение для загрузки и загрузки файлов с FTP-сервера с помощью ftplib.
Каждый раз, когда загружаются некоторые куски данных, я хочу обновить строку выполнения текста, даже если это всего лишь номер.
Но я не хочу стирать весь текст, который был напечатан на консоли. (Выполнение "очистить", а затем распечатать обновленный процент.)
Ответы
Ответ 1
Простой, настраиваемый индикатор выполнения
Вот совокупность многих ответов ниже, которые я использую регулярно (импорт не требуется).
# 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
Обновление
В комментариях обсуждалась опция, позволяющая динамически настраивать индикатор выполнения в соответствии с шириной окна терминала. Хотя я не рекомендую это, здесь gist, который реализует эту функцию (и отмечает предостережения).
Ответ 2
Запись '\ r' вернет курсор к началу строки.
Здесь отображается процентный счетчик:
import time
import sys
for i in range(100):
time.sleep(1)
sys.stdout.write("\r%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]
![tqdm repl session]()
Ответ 4
Напишите \r
на консоли. Это "возврат каретки" , который вызывает весь текст после его эхо в начале строки. Что-то вроде:
def update_progress(progress):
print '\r[{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\r' % (bar, percents, '%', suffix))
sys.stdout.flush() # As suggested by Rom Ruben
![enter image description here]()
Ответ 6
Попробуйте библиотеку click, написанную Моцартом из Python, Армином Ронахером.
$ 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 docs:
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("\rPercent: [{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
, чтобы упростить задачу:)
[править]
Возможно, проще не слово для проклятий. Но если вы хотите создать полномасштабный cui, а проклятия позаботятся о вас много.
[править]
Поскольку старая ссылка мертва, я поставил свою собственную версию Python Progressbar, перейдите сюда: 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))+("\r [ %d"%i+"% ] "))
sys.stdout.flush()
Выход
[29%] ===================
Ответ 11
и, просто чтобы добавить в кучу, здесь объект, который вы можете использовать
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
Это чаще всего считается "сверху", но это удобно, когда вы его много используете.
Ответ 12
Запустите это в командной строке Python ( не в любой среде IDE или в среде разработки):
>>> import threading
>>> for i in range(50+1):
... threading._sleep(0.5)
... print "\r%3d" % i, ('='*i)+('-'*(50-i)),
Хорошо работает в моей системе Windows.
Ответ 13
Установите 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]
Ответ 14
И много учебников, ожидающих, что они будут googled.
Ответ 15
Я использую прогресс от reddit. Мне нравится, потому что он может печатать ход для каждого элемента в одной строке и не должен удалять распечатки из программы.
Изменить: фиксированная ссылка
Ответ 16
основываясь на приведенных выше ответах и других подобных вопросах о шаге прогресса CLI, я думаю, что я получил общий общий ответ на все из них. Проверьте его на fooobar.com/questions/27978/...
Таким образом, код выглядит следующим образом:
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%
Ответ 17
Я рекомендую использовать 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)
Ответ 18
Попробуйте установить этот пакет: 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
Ответ 19
import sys
def progresssbar():
for i in range(100):
time.sleep(1)
sys.stdout.write("%i\r" % i)
progressbar()
ПРИМЕЧАНИЕ. Если вы запустите это в интерактивном interepter, вы получите лишние номера, напечатанные
Ответ 20
lol я просто написал целую вещь для этого
heres код помните, что вы не можете использовать unicode при выполнении блока ascii, я использую 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
|█████ |
Ответ 21
С большими советами выше я разрабатываю индикатор выполнения.
Однако я хотел бы указать на некоторые недостатки
-
Каждый раз, когда индикатор выполнения очищается, он запускается на новой строке
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='')
Ответ 22
Очень простое решение - поместить этот код в ваш цикл:
Поместите это в тело (то есть в начало) вашего файла:
import sys
Поместите это в тело вашей циклы:
sys.stdout.write("-") # prints a dash for each iteration of loop
sys.stdout.flush() # ensures bar is displayed incrementally
Ответ 23
Код для строки выполнения терминала 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()
Ответ 24
Объединяя некоторые из идей, которые я нашел здесь, и добавив приблизительное время:
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)
Ответ 25
Ну вот код, который работает, и я тестировал его перед публикацией:
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()
Плюсы:
- 20 символов (1 символ на каждые 5 (число мудрых))
- Пользовательские символы заполнения
- Пользовательские пустые символы
- Halt (любое число ниже 0)
- Готово (100 и любое число выше 100)
- Счетчик хода (0-100 (ниже и выше используется для специальных функций))
- Процентное число рядом с bar, и это одна строка
Минусы:
- Поддерживает только целые числа (его можно модифицировать, чтобы поддерживать их, сделав разделение целочисленным делением, поэтому просто измените
prog2 = prog/5
на prog2 = int(prog/5)
)
Ответ 26
Здесь мое решение Python 3:
import time
for i in range(100):
time.sleep(1)
s = "{}% Complete".format(i)
print(s,end=len(s) * '\b')
'\ b' - обратная косая черта для каждого символа в вашей строке.
Это не работает в окне Windows cmd.
Ответ 27
от 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()
Ответ 28
Модуль 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()
Ответ 29
https://pypi.python.org/pypi/progressbar2/3.30.2
Progressbar2 - это хорошая библиотека для базового уровня прогресса ascii для командной строки время импорта область прогресса импорта
bar = progressbar.ProgressBar()
for i in bar(range(100)):
time.sleep(0.02)
bar.finish()
https://pypi.python.org/pypi/tqdm
tqdm является альтернативой progressbar2, и я думаю, что он используется в pip3, но я не уверен в этом
from tqdm import tqdm
for i in tqdm(range(10000)):
...
Ответ 30
Я написал простую панель прогресса:
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% [###### ]
out on complete:
100% [ done in 9 sec ]