第一種(簡單).python實現簡單的進度條的方法
import sys for i in range(101): s="\r%d%% %s"%(i,"#"*i) #\r表示回車但是不換行,利用這個原理進行百分比的刷新 sys.stdout.write(s) #向標准輸出終端寫內容 sys.stdout.flush() #立即將緩存的內容刷新到標准輸出 import time time.sleep(0.1) #設置延遲查看效果
第二種(復雜/美觀)(推薦):
#!/usr/bin/python3 # -*- coding:utf-8 -*- import sys import time from urllib import request ''' urllib.urlretrieve 的回調函數: def callbackfunc(blocknum, blocksize, totalsize): @blocknum: 已經下載的數據塊 @blocksize: 數據塊的大小 @totalsize: 遠程文件的大小 ''' def Schedule(blocknum, blocksize, totalsize): speed = (blocknum * blocksize) / (time.time() - start_time) # speed_str = " Speed: %.2f" % speed speed_str = " Speed: %s" % format_size(speed) recv_size = blocknum * blocksize # 設置下載進度條 f = sys.stdout pervent = recv_size / totalsize percent_str = "%.2f%%" % (pervent * 100) n = round(pervent * 50) s = ('#' * n).ljust(50, '-') f.write(percent_str.ljust(8, ' ') + '[' + s + ']' + speed_str) f.flush() # time.sleep(0.1) f.write('\r') # 字節bytes轉化K\M\G def format_size(bytes): try: bytes = float(bytes) kb = bytes / 1024 except: print("傳入的字節格式不對") return "Error" if kb >= 1024: M = kb / 1024 if M >= 1024: G = M / 1024 return "%.3fG" % (G) else: return "%.3fM" % (M) else: return "%.3fK" % (kb) if __name__ == '__main__': # print(format_size(1222222222)) start_time = time.time() filename = 'test.data' url = 'http://ip:port/path/speed.test' request.urlretrieve(url, filename, Schedule)
小提示:第二種注意把time.sleep(0.1)打開,不然看不到下載的時候可能看不到進度條
參考鏈接:https://yq.aliyun.com/articles/548109
https://www.cnblogs.com/standby/p/7384187.html