본문 바로가기

Dev/Python

콘솔에서 프로그레스바 출력하기

windows 환경에서만 테스트해보았다. 개행 처리가 windows와 linux, unix가 다르니 이기종 환경에서는 동작이 다를수도 있음.

# Print iterations progress
import sys

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)
    sys.stdout.write('\r')
    sys.stdout.write(f'%s |%s| %s%% %s (%d/%d)' % (prefix, bar, percent, suffix, iteration, total))
    sys.stdout.flush()

    if iteration == total:
        print()