用Python基本库实现进度条
用Python基本库实现进度条效果
几个要点:
1. \r,重置光标
2. time.perf_counter,计算运行时间
3. 用format控制输出格式
1 #progress bar2 2 #The sytle of prgress bar will be shown as below 3 ##16%[********->------------------------------------------]0.86s 4 #It will be divided into three part:ratio,progress bar,duration time 5 # \r, first use \r to force cursor goto beginng of a line every time 6 # 7 import time 8 scale = 50 #define the scope of char shown as progress bar 9 print('Getting Start'.center(scale//2,'-')) 10 11 start = time.perf_counter() 12 13 for i in range(scale + 1): 14 ratio = i/scale 15 star = '*' * i 16 hyphen = '-' * (scale - i) 17 dur = time.perf_counter() - start 18 print('\r{:>4.0%}[{}->{}]{:.2f}s'.format(ratio,star,hyphen,dur),end='') 19 time.sleep(0.1)