tqdm, clear_output 같이 사용하는 방법

2021. 10. 5. 22:38꿀팁 분석 환경 설정/파이썬 개발 팁

728x90

주피터에서 학습을 시키다 보면, 그림도 띄우고 싶고, tqdm으로 진행과정도 같이 보고 싶을 때가 있다.

하지만 이 2개를 동시에 하기 위해서는 일단 그림을 매번 쓰고 지우는 코드가 필요한데, 바로 clear_output이라는 코드이다.

 

 

from IPython.display import clear_output
plt.plot(np.arange(0,10))
plt.show()
clear_output(wait=True)

위와 같이 작성을 하게 되면, 그림을 그리고 지우는 코드가 된다.

 

하지만 이걸 tqdm과 같이 하게 되면 tqdm bar도 지워지는 현상이 있다. 

그래서 찾아보니 아래 링크와 같이 하면 된다는 것을 알았다.

이것을 하나의 주피터 셀안에 넣으면 그림도 그리면서 tqdm이 진행된다.

 

import time
import numpy as np
import matplotlib.pyplot as plt
from tqdm.auto import trange

from IPython import display
from ipywidgets import Output

out = Output()
display.display(out)
for i in trange(10):
    with out:
        plt.plot(np.random.randn(100))
        plt.show()
        display.clear_output(wait=True)
    time.sleep(1)

 

 

한 가지 아쉬운 점은 주피터 셀을 분리해서 loop 같은 것을 함수로 만들게 되면, 함수를 정의한 부분에서 그림이 나오게 되는 경우를 발견했다.

그래도 2개를 같이 볼 수 있으려면, 이런 식으로 쉽게 할 수 있으니 추천한다.

 

 

https://github.com/tqdm/tqdm/issues/818

 

Cannot redraw tqdm_notebook Hbox progress bar after calling clear_output(), only ascii shown · Issue #818 · tqdm/tqdm

I have visited the source website, and in particular read the known issues I have searched through the issue tracker for duplicates I have mentioned version numbers, operating system and environmen...

github.com

 

728x90