Pasek postępu tekstu w konsoli [zamknięty]

Czy jest dobry sposób, aby wykonać następujące czynności?

Napisałem prostą aplikację konsolową do wysyłania i pobierania plików z serwera FTP za pomocą ftplib.

Za każdym razem, gdy pobierane są jakieś fragmenty danych, chcę zaktualizować pasek postępu tekstu, nawet jeśli jest to tylko liczba.

Ale nie chcę kasować całego tekstu, który został wydrukowany na konsoli. (Robi "wyczyść", a następnie drukuje zaktualizowany procent.)

Author: Tshepang, 2010-07-04

30 answers

Oto zestawienie wielu z poniższych odpowiedzi, z których regularnie korzystam.

# 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('\r%s |%s| %s%% %s' % (prefix, bar, percent, suffix), end = '\r')
    # Print New Line on Complete
    if iteration == total: 
        print()

# 
# Sample Usage
# 

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)

# Sample Output
Progress: |█████████████████████████████████████████████-----| 90.0% Complete
 236
Author: Greenstick,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-07-06 17:39:57

Zapisanie '\r' spowoduje przesunięcie kursora z powrotem na początek wiersza.

Wyświetla licznik procentowy:

import time
import sys

for i in range(100):
    time.sleep(1)
    sys.stdout.write("\r%d%%" % i)
    sys.stdout.flush()
 277
Author: Stephen,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-08-01 21:41:48

Napisz \r do konsoli. Jest to "powrót karetki" , który powoduje, że cały tekst po nim jest odbijany echem na początku wiersza. Coś w stylu:

def update_progress(progress):
    print '\r[{0}] {1}%'.format('#'*(progress/10), progress)

Co da ci coś w rodzaju: [ ########## ] 100%

 104
Author: aviraldg,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-07-04 00:42:12

Tqdm: dodaj miernik postępu do pętli w sekundę:

>>> 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]

sesja tqdm repl

 97
Author: jfs,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-03-30 11:56:37

Jest to mniej niż 10 linijek kodu.

Sedno tutaj: 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

Tutaj wpisz opis obrazka

 54
Author: Vladimir Ignatyev,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-24 18:25:50

Wypróbuj Kliknij bibliotekę napisaną przez Mozarta Pythona, Armina Ronachera.

$ pip install click # both 2 and 3 compatible

Aby utworzyć prosty pasek postępu:

import click

with click.progressbar(range(1000000)) as bar:
    for i in bar:
        pass 

Tak to wygląda:

# [###-------------------------------]    9%  00:01:14

Dostosuj do swoich serc treść:

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

Custom look:

(_(_)===================================D(_(_| 100000/100000 00:00:02

Jest jeszcze więcej opcji, zobacz 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)
 50
Author: The Unfun Cat,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-06-09 18:42:41

Zdaję sobie sprawę, że jestem spóźniony na grę, ale tutaj jest nieco Mniam styl (Red Hat), który napisałem (nie chodzi tu o 100% dokładności, ale jeśli używasz paska postępu dla tego poziomu dokładności, to i tak się mylisz): {]}

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()

Powinno wytworzyć coś wyglądającego TAK:

Percent: [##############      ] 69%

... gdzie nawiasy pozostają nieruchome i zwiększają się tylko skróty.

To może działać lepiej jako dekorator. Na kolejny dzień...
 29
Author: JoeLinux,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-12-03 14:11:23

Sprawdź tę bibliotekę:

Posiada wiele funkcji, w tym pasek postępu:

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)

Ten link zapewnia szybki przegląd jego funkcji

 17
Author: scripts,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-01-16 12:25:12

Oto ładny przykład paska postępu napisanego w Pythonie: http://nadiana.com/animated-terminal-progress-bar-in-python

Ale jeśli chcesz napisać to sam. Możesz użyć modułu curses, aby wszystko było łatwiejsze:)

[edytuj] Być może łatwiejsze to nie słowo na przekleństwa. Ale jeśli chcesz stworzyć pełnowymiarowe cui, to przekleństwa zajmą się wieloma rzeczami dla Ciebie.

[edytuj] Ponieważ stary link jest martwy, wstawiłem własną wersję Pythona Progressbar, get it here: https://github.com/WoLpH/python-progressbar

 11
Author: Wolph,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-02-01 20:07:21
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()

Wyjście

[ 29% ] ===================

 10
Author: ashish2py,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-04-21 12:24:04

I, aby dodać do stosu, oto obiekt, którego możesz użyć

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"

Wyniki w:

starting things:
  100% [=================================================================]
done

Jest to najczęściej uważane za "over the top", ale jest przydatne, gdy używasz go dużo

 7
Author: FraggaMuffin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-05-28 08:19:52

Uruchom to w wierszu poleceń Pythona (nie w żadnym środowisku IDE lub deweloperskim):

>>> import threading
>>> for i in range(50+1):
...   threading._sleep(0.5)
...   print "\r%3d" % i, ('='*i)+('-'*(50-i)),

Działa dobrze na moim systemie Windows.

 6
Author: PaulMcG,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-07-04 17:50:46

Install tqdm.(pip install tqdm) i użyj go w następujący sposób:

import time
from tqdm import tqdm
for i in tqdm(range(1000)):
    time.sleep(0.01)

To 10-sekundowy pasek postępu, który wyświetli coś takiego:

47%|██████████████████▊                     | 470/1000 [00:04<00:05, 98.61it/s]
 5
Author: Tux,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-11-25 13:11:04
 4
Author: Andy Mikhaylenko,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-12-26 09:24:40

Używam progress from reddit . Podoba mi się, ponieważ może drukować postępy dla każdego elementu w jednej linii i nie powinien usuwać wydruków z programu.

Edit: fixed link

 4
Author: Ib33X,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-07-06 18:05:19

W oparciu o powyższe odpowiedzi i inne podobne pytania dotyczące paska postępu CLI, myślę, że mam ogólną wspólną odpowiedź na wszystkie z nich. Sprawdź na https://stackoverflow.com/a/15860757/2254146

Podsumowując, kod jest taki:

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()

Wygląda jak

Procent: [##########] 99.0%

 3
Author: Brian Khuu,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-23 12:34:44

Polecam użycie tqdm- https://pypi.python.org/pypi/tqdm - co ułatwia zamianę dowolnego iterable lub procesu w pasek postępu i zajmuje się wszystkimi potrzebnymi terminalami.

Z dokumentacji: "tqdm może łatwo obsługiwać wywołania zwrotne/Hooki i ręczne aktualizacje. Oto przykład z 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)
 3
Author: Malcolm Box,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-09-13 15:26:42
import sys
def progresssbar():
         for i in range(100):
            time.sleep(1)
            sys.stdout.write("%i\r" % i)

progressbar()

Uwaga: jeśli uruchomisz to w interaktywnym interepterze, otrzymasz wydrukowane dodatkowe liczby

 2
Author: Ramchandra Apte,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-07-25 14:22:21

Lol właśnie napisałem całą rzecz do tego heres kod należy pamiętać, że nie można używać unicode podczas robienia bloku ascii używam 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()

And you call it like so

print "loading something awesome"
load("|", "|", 10, .01)

Więc wygląda to tak

loading something awesome
|█████     |
 2
Author: ryan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-02-14 16:32:31

[2]}z powyższymi wspaniałymi poradami wypracowuję pasek postępu.

Chciałbym jednak zwrócić uwagę na pewne niedociągnięcia

  1. Za każdym razem, gdy pasek postępu zostanie spłukany, rozpocznie się on w nowej linii

    print('\r[{0}]{1}%'.format('#' * progress* 10, progress))  
    

    Tak:
    [] 0%
    [#]10%
    [##]20%
    [###]30%

2.Nawias kwadratowy'] 'i liczba procentowa po prawej stronie przesuwają się w prawo, gdy' # # # ' wydłuża się.
3. Błąd wystąpi, jeśli wyrażenie "progress / 10" nie można zwrócić liczby całkowitej.

I poniższy kod rozwiąże powyższy problem.

def update_progress(progress, total):  
    print('\r[{0:10}]{1:>2}%'.format('#' * int(progress * 10 /total), progress), end='')
 2
Author: Storm-Eyes,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-04-13 10:03:38

Kod dla paska postępu terminala Pythona

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()
 1
Author: emd_22,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-19 08:14:24

Zestawiając kilka pomysłów, które tu znalazłem, i dodając szacowany czas pozostały:

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)
 1
Author: Ivan Chaer,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-10-19 22:10:42

Spróbuj zainstalować ten pakiet: pip install progressbar2 :

import time
import progressbar

for i in progressbar.progressbar(range(100)):
    time.sleep(0.02)

Progresssbar github: https://github.com/WoLpH/python-progressbar

 1
Author: Chris Cui,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-05-25 23:11:49

Bardzo prostym rozwiązaniem jest umieszczenie tego kodu w pętli:

Umieść to w ciele (tj. na górze) Twojego pliku:

import sys

Włóż to do ciała swojej pętli:

sys.stdout.write("-") # prints a dash for each iteration of loop
sys.stdout.flush() # ensures bar is displayed incrementally
 1
Author: Richard Hayman-Joyce,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-06-12 14:37:15

Cóż tutaj jest kod, który działa i Przetestowałem go przed wysłaniem:

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()

PLUSY:

  • Pasek 20 znaków (1 znak na każde 5 (Liczba))
  • własne znaki wypełnienia
  • własne puste znaki
  • Halt (dowolna liczba poniżej 0)
  • zrobione (100 i dowolna liczba powyżej 100)
  • Liczba postępu (0-100 (poniżej i powyżej używane dla funkcji specjalnych))
  • Liczba procentowa obok paska i jest to pojedyncza linia

Wady:

  • obsługuje tylko liczby całkowite (można je zmodyfikować, aby je obsługiwać, zmieniając dzielenie na liczbę całkowitą, więc po prostu zmień prog2 = prog/5 na prog2 = int(prog/5))
 0
Author: Cold Diamondz,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-07-24 17:22:44

Oto moje rozwiązanie Pythona 3:

import time
for i in range(100):
    time.sleep(1)
    s = "{}% Complete".format(i)
    print(s,end=len(s) * '\b')

'\b ' jest odwrotnym ukośnikiem dla każdego znaku w łańcuchu. Nie działa to w oknie cmd systemu Windows.

 0
Author: Matt-the-Bat,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-12-26 05:39:05

Funkcja Z Greenstick dla 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()
 0
Author: Edmond de Martimprey,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-04-20 09:24:38

Moduł Pythona progressbar jest dobrym wyborem. Oto mój typowy kod:

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()
 0
Author: Aimin Huang,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-26 05:49:30

Https://pypi.python.org/pypi/progressbar2/3.30.2

Progressbar2 jest dobrą biblioteką dla ASCII base progressbar dla linii poleceń czas importu import progressbar

bar = progressbar.ProgressBar()
for i in bar(range(100)):
    time.sleep(0.02)
bar.finish()

Https://pypi.python.org/pypi/tqdm

Tqdm jest alternatywą progressbar2 i myślę, że używa się go w pip3, ale nie jestem tego pewien

from tqdm import tqdm
for i in tqdm(range(10000)):
...
 0
Author: Antoine Boucher,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-06-15 14:52:20

Napisałem prosty progresbar:

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)

Jak widać, ma: długość paska, prefiks i sufiks, wypełniacz, spację, tekst w pasku na 100%(oncomp) i granice

Oto przykład:

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)

W toku:

30% [######              ]

Out on complete:

100% [   done in 9 sec   ] 
 0
Author: jenkins,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-07-01 11:51:08