본문 바로가기
Software coding skill(python, web등)

tqdm 사용법 - python 진행률 프로세스바

by 호빵님 2020. 2. 15.
반응형

파이썬으로 어떤 작업을 수행중인데, 프로그램이 내가 의도한 데로 돌아가고 있는 중인가, 진행상황이 궁금할 때가 있다. 시간이 걸리는 작업의 경우에 더 이런 상태 확인이 필요하다. 

파이썬 모듈중에 tqdm이라는 것이 이 용도로 쓰이고 있다.

 

사용법

tqdm is very versatile and can be used in a number of ways. The three main ones are given below.

tqdm은 아주 변하기 쉽고 많은 방법으로 사용될 수 있다. 아래 세가지 주요 방법들이 있다.

 


 

Iterable-based

Wrap tqdm() around any iterable:

어느 이터러블이든 tqdm()로 감싼다. 리스트도 가능. 이터러블이 증가하는 것에 따라서, 진행률 증가.

from tqdm import tqdm
import time

text = ""
for char in tqdm(["a", "b", "c", "d"]):
    time.sleep(0.25)
    text = text + char
100%|██████████| 4/4 [00:01<00:00,  3.93it/s]

 

range(100)같은 것도 감싸면됨. 옵션 desc 에 진행 작업에 대한 설명을 추가 가능하다. 옵션 mininterval에 최소 업데이트 주기를 설정 가능하다.

from tqdm import tqdm
import time
for ii in tqdm(range(100), desc="tqdm example", mininterval=0.01): 
    # print(ii) 
    time.sleep(0.1)
tqdm example: 100%|██████████| 100/100 [00:10<00:00,  9.78it/s]

 

tqdm파라미터 설명

  • iterable : 반복자 객체
  • desc : 진행바 앞에 텍스트 출력
  • total : int, 전체 반복량
  • leave : bool, default로 True. (진행상태 잔상이 남음)
  • ncols : 진행바 컬럼길이. width 값으로 pixel 단위로 보임.
  • mininterval, maxinterval : 업데이트 주기. 기본은 mininterval=0.1 sec, maxinterval=10 sec
  • miniters : Minimum progress display update interval, in iterations.
  • ascii : True로 하면 '#'문자로 진행바가 표시됨.
  • initial : 진행 시작값. 기본은 0
  • bar_format : str
  • 전체 작업량을 알고 있고, 처리된 량으로 진행바를 표시할 경우에, update()로 진행량 추가

메소드

 

  • clear() : 삭제

  • refresh() : 강제 갱신

 

 

trange(i) is a special optimised instance of tqdm(range(i)):

trange(i)는 특별한 최적화 인스턴스다. tqdm(range(i))와 같은 기능이다.

for i in trange(100):
    time.sleep(0.01)
100%|██████████| 100/100 [00:01<00:00, 91.13it/s]

 

Instantiation outside of the loop allows for manual control over tqdm():

루프 밖에서 수동 tqdm 인스턴스 선언이 허용된다.

pbar = tqdm(["a", "b", "c", "d"])
for char in pbar:
    time.sleep(0.25)
    pbar.set_description("Processing %s" % char)
Processing d: 100%|██████████| 4/4 [00:01<00:00,  3.93it/s]

 


 

Manual

Manual control on tqdm() updates by using a with statement:

with구문을 사용해서 tqdm을 수동으로 컨트롤한다. update()로 수동으로 진행률을 증가 시킨다.

with tqdm(total=100) as pbar:
    for i in range(10):
        time.sleep(0.1)
        pbar.update(10) #10씩 증가
100%|██████████| 100/100 [00:01<00:00, 97.84it/s]

 

If the optional variable total (or an iterable with len()) is provided, predictive stats are displayed.

옵션 total이 제공되면, 예상되는 현재 상태가 디스플레이된다.

with is also optional (you can just assign tqdm() to a variable, but in this case don't forget to del or close() at the end: 

with적용하는 것도 옵션중 하나이다.

너가 그냥 tqdm함수만을 변수에 할당할 수도 있는데, 이렇게 쓰는 경우에는 끝에 del이나 close하는 것을 잊지마라.

pbar = tqdm(total=100)
for i in range(10):
    time.sleep(0.1)
    pbar.update(10)
pbar.close()
100%|██████████| 100/100 [00:01<00:00, 98.05it/s]

 

 


 

Module

Perhaps the most wonderful use of tqdm is in a script or on the command line.

아마 가장 엄청난 tqdm사용법은 스크립트나 커맨드라인 안에 있다.

 

Simply inserting tqdm (or python -m tqdm) between pipes will pass through all stdin to stdout while printing progress to stderr.

간단하게 tqdm(이나 python -m tqdm)을 pipe들 사이에 넣는다. stdin에서 stdout을 통과해서 지나가도록 한다.

 

The example below demonstrated counting the number of lines in all Python files in the current directory, with timing information included.

아래 예제는 현재 디렉토리내에 모든 python file내의 라인 숫자를 카운팅한다. 타이밍 정보를 포함한다.

$ time find . -name '*.py' -type f -exec cat \{} \; | wc -l
857365

real    0m3.458s
user    0m0.274s
sys     0m3.325s

$ time find . -name '*.py' -type f -exec cat \{} \; | tqdm | wc -l
857366it [00:03, 246471.31it/s]
857365

real    0m3.585s
user    0m0.862s
sys     0m3.358s

 

Note that the usual arguments for tqdm can also be specified.

보통 tqdm인자들은 또한 특정화될 수 있다.

$ find . -name '*.py' -type f -exec cat \{} \; |
    tqdm --unit loc --unit_scale --total 857366 >> /dev/null
100%|███████████████████████████████████| 857K/857K [00:04<00:00, 246Kloc/s]

 

Backing up a large directory?

큰 디렉토리를 백업 하시겠습니까?

$ 7z a -bd -r backup.7z docs/ | grep Compressing |
    tqdm --total $(find docs/ -type f | wc -l) --unit files >> backup.log
100%|███████████████████████████████▉| 8014/8014 [01:37<00:00, 82.29files/s]
반응형