1. 程式人生 > >python 自制進度條 重新實現print

python 自制進度條 重新實現print

import sys, time

class SP():
    i = 0 # 當前的處理進度
    data=None
    it=None
    max_arrow=25
    max_steps=0
    infoDone="OK"
    # 初始化函式,需要知道總共的處理次數
    def __init__(self):
        pass
    def __iter__(self):
        return self

    def __next__(self):
        if self.i!=0:
            self.show()
        self.i+=1
if self.i==self.max_steps+1: self.close() return next(self.it) def __call__(self, data): self.data = data self.it=iter(self.data) self.max_steps=len(data ) return self def clear(self): sys.stdout.write(" "*10+'\r') sys.stdout.flush() def
print(self,t):
print(t+" "*100) self.show() def show(self): if self.i <= self.max_steps: num_arrow = int(self.i * self.max_arrow / self.max_steps) #計算顯示多少個'>' num_line = self.max_arrow - num_arrow #計算顯示多少個'-' percent = self.i * 100.0
/ self.max_steps #計算完成進度,格式為xx.xx% process_bar = '[' + '>' * num_arrow + '-' * num_line + ']'\ + '%.2f' % percent + '%' + '\r' #帶輸出的字串,'\r'表示不換行回到最左邊 sys.stdout.write(process_bar) #這兩句列印字元到終端 sys.stdout.flush() def close(self): print('') print(self.infoDone) sp=SP()