Programming

콘솔의 텍스트 진행률 표시 줄

procodes 2020. 2. 25. 22:57
반응형

콘솔의 텍스트 진행률 표시 줄


다음을 수행하는 좋은 방법이 있습니까?

ftplib을 사용하여 FTP 서버에서 파일을 업로드하고 다운로드하는 간단한 콘솔 앱을 작성했습니다.

일부 데이터 청크를 다운로드 할 때마다 텍스트 진행률 표시 줄이 숫자 일지라도 업데이트하고 싶습니다.

그러나 콘솔에 인쇄 된 모든 텍스트를 지우고 싶지 않습니다. ( "클리어"를 한 다음 업데이트 된 백분율을 인쇄하십시오.)


간단하고 사용자 정의 가능한 진행률 표시 줄

아래에는 정기적으로 사용하는 많은 답변이 있습니다 (수입 필요 없음).

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

참고 : 이것은 Python 3 용입니다. 파이썬 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

최신 정보

진행률 표시 줄이 터미널 창 너비에 맞게 동적으로 조정될 수있는 옵션에 대한 주석에서 설명이있었습니다. 권장하지는 않지만 이 기능을 구현 하는 요점 은 다음과 같습니다.


'\ r'을 쓰면 커서가 줄의 처음으로 돌아갑니다.

백분율 카운터가 표시됩니다.

import time
import sys

for i in range(100):
    time.sleep(1)
    sys.stdout.write("\r%d%%" % i)
    sys.stdout.flush()

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 세션


\r콘솔 에을 씁니다 . 이것은 "캐리지 리턴" 으로, 줄의 시작 부분에 모든 텍스트가 에코됩니다. 다음과 같은 것 :

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

그것은 당신에게 다음과 같은 것을 줄 것입니다 : [ ########## ] 100%


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

여기에 이미지 설명을 입력하십시오


Mozart of 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)

나는 게임에 늦었다는 것을 알고 있지만 여기에 내가 쓴 약간 Yum 스타일 (Red Hat)이 있습니다. 어쨌든 잘못되었습니다) :

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%

... 괄호가 고정되어 있고 해시 만 증가합니다.

데코레이터로 더 잘 작동 할 수 있습니다. 다른 날에 ...


이 라이브러리를 확인하십시오 : 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)

링크 는 기능에 대한 간략한 개요를 제공합니다


다음은 Python으로 작성된 진행률 표시 줄의 좋은 예입니다. http://nadiana.com/animated-terminal-progress-bar-in-python

그러나 직접 작성하고 싶다면. 당신은 curses일을 더 쉽게하기 위해 모듈을 사용할 수 있습니다 :)

[편집] 아마도 더 쉬운 것은 저주라는 단어가 아닙니다. 그러나 저주보다 당신이 본격적인 cui를 만들고 싶다면 당신을 위해 많은 것들을 처리합니다.

[편집] 오래된 링크가 죽었 기 때문에 내 자신의 Python Progressbar 버전을 설치했습니다. https://github.com/WoLpH/python-progressbar


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


더미에 추가하기 위해 사용할 수있는 개체는 다음과 같습니다.

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

가장 일반적으로 "최상의"것으로 간주되지만 많이 사용할 때 편리합니다.


이 프로그램을 실행 파이썬 명령 줄에서 ( 아니 어떤 IDE 또는 개발 환경에서)

>>> import threading
>>> for i in range(50+1):
...   threading._sleep(0.5)
...   print "\r%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]

그리고 많은 튜토리얼이 구글을 기다리고 있습니다.


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

이 패키지를 설치하십시오 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


import sys
def progresssbar():
         for i in range(100):
            time.sleep(1)
            sys.stdout.write("%i\r" % i)

progressbar()

참고 : 대화 형 인터셉터에서 이것을 실행하면 여분의 숫자가 인쇄됩니다


롤 나는 방금 이것에 대한 모든 것을 썼다. 코드는 블록 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
|█████     |

위의 훌륭한 조언으로 진행률 표시 줄을 해결합니다.

그러나 몇 가지 단점을 지적하고 싶습니다.

  1. 진행률 표시 줄이 플러시 될 때마다 새 줄에서 시작됩니다.

    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='')

매우 간단한 해결책은이 코드를 루프에 넣는 것입니다.

이것을 파일의 본문 (즉 상단)에 넣으십시오.

import sys

이것을 루프 본문에 넣으십시오.

sys.stdout.write("-") # prints a dash for each iteration of loop
sys.stdout.flush() # ensures bar is displayed incrementally

파이썬 터미널 진행률 표시 줄 코드

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

내가 찾은 아이디어 중 일부를 정리하고 남은 예상 시간을 추가하십시오.

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)

다음은 작동하는 코드이며 게시하기 전에 테스트했습니다.

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 자 표시 줄 (5 자당 1 자)
  • 맞춤 채우기 문자
  • 사용자 정의 빈 문자
  • 중지 (0보다 작은 숫자)
  • 완료 (100 및 100보다 큰 숫자)
  • 진행 횟수 (0-100 (특수 기능에 사용됨) 이상)
  • 막대 옆의 백분율 숫자이며 한 줄입니다.

단점 :

  • 정수 만 지원합니다 (나눗셈을 정수 나누기로 만들어서 지원하도록 수정할 수 있으므로로 변경 prog2 = prog/5하십시오 prog2 = int(prog/5))

다음은 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 창에서는 작동하지 않습니다.


2.7 용 Greenstick의 기능 :

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

파이썬 모듈 진행률 표시 줄 은 좋은 선택입니다. 일반적인 코드는 다음과 같습니다.

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

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)):
...

간단한 진행률 표시 줄을 작성했습니다.

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   ] 

참고 URL : https://stackoverflow.com/questions/3173320/text-progress-bar-in-the-console



반응형