tqdm을 사용할 때, progress bar 사용 후에 print()를 하는데 print()가 먼저 출력되고 progress bar가 출력되는 상황을 가끔 볼 수 있다. (주로 tqdm에 넣는 iterable 객체의 길이가 짧을 때)

 

# example
from tqdm import tqdm

print('처음 출력 내용')

for i in tqdm([1,2,3]):
    pass

print('마지막 출력 내용')

 

왼쪽은 목표로 한 출력형식, 오른쪽은 출력 순서가 꼬인 모습

 

 

이런 현상이 발생하는 이유는 tqdm은 print()와 달리 stderr스트림을 통해 콘솔에 출력되기 때문이다.

 

만약 tqdm의 progress bar와 print()가 같은 스트림을 통해 출력된다면 순서대로 출력 될 것이다.

(같은 통로를 사용하기 때문에)

하지만 progress bar와 print()는 각각 stderr, stdout스트림을 통해 출력이 된다.

따라서 처리속도에 따라 출력 순서가 바뀔 수 있다.

 

https://en.wikipedia.org/wiki/Standard_streams

 

 

간단한 해결방법은 progress bar, print()모두 같은 스트림을 사용하도록 바꾸면 된다.

# example, 이걸 추천
from tqdm import tqdm
import sys

print('처음 출력 내용')

for i in tqdm([1,2,3], file=sys.stdout):
    pass

print('마지막 출력 내용')

################ or ################

# example
from tqdm import tqdm
import sys

print('처음 출력 내용', file=sys.stderr)

for i in tqdm([1,2,3]):
    pass

print('마지막 출력 내용', file=sys.stderr)

 

각 코드의 실행결과