進度條python
import sys, time class ShowProcess(object): """ 顯示處理進度的類 調用該類相關函數便可實現處理進度的顯示 """ # i = 0 # 當前的處理進度 # max_steps = 0 # 總共須要處理的次數 # max_arrow = 50 #進度條的長度 # 初始化函數,須要知道總共的處理次數 def __init__(self, max_steps): self.max_steps = max_steps # 總共須要處理的次數 self.max_arrow = 50 # 進度條的長度 self.i = 0 # 當前的處理進度 # 顯示函數,根據當前的處理進度i顯示進度 # 效果爲[>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>]100.00% def show_process(self, i=None): if i is not None: self.i = i num_arrow = int(self.i * self.max_arrow / self.max_steps) # 計算顯示多少個'>' num_line = self.max_arrow - num_arrow # 計算顯示多少個'-' print(num_arrow,">") print(num_line,"-") percent = self.i * 100.0 / self.max_steps # 計算完成進度,格式爲xx.xx% print(percent,'百分比') process_bar = '\r' + '[' + '>' * num_arrow + '-' * num_line +']' + '%.2f' % percent + '%' #帶輸出的字符串,'\r'表示不換行回到最左邊 sys.stdout.write(process_bar) # 這兩句打印字符到終端 sys.stdout.flush() self.i += 1 def close(self, words='done'): print('') print(words) self.i = 1 if __name__ == '__main__': max_steps = 1000 process_bar = ShowProcess(max_steps) for i in range(max_steps + 1): process_bar.show_process() time.sleep(0.05) process_bar.close()