用 python 的生成器制作數據傳輸進度條
阿新 • • 發佈:2017-07-04
flush code 現在 發送 nbsp error: 處理 stop next
整個過程中有幾個數據
1 已經傳輸的數據received_size
2 文件大小tatol
a = received_size/tatol b = a*100 其中 , a是已傳輸數據占總數據的百分比, b就是已經傳輸的進度, 總進度為100
現在只要實現進度有更新就打印#
1 # _*_coding:utf-8_*_ 2 # Author:Jaye He 3 import time 4 5 6 def show_progress(total): 7 received_size = 0 # 已接收文件大小 8 current_percent = 0 #接收進度 9 while received_size < total: 10 if int((received_size/total)*100) > current_percent: 11 print(‘#‘, end=‘‘, flush=True) 12 current_percent = int((received_size/total)*100) 13 received_size = yield 14 15 16 total = 100000 #文件總大小 17 18 # 啟動生成器progress 19 progress = show_progress(total) 20 # 開始啟動必須要用.__next__()啟動,不能直接用send 21 # 否則出現TypeError: can‘t send non-None value to a just-started generator 22 progress.__next__() 23 24 received_size = 0 # 模擬已接收的數據大小 25 26 # 模擬數據傳輸 27 while received_size < total:28 time.sleep(0.3) # 模擬每次傳輸數據花費的時間 29 received_size += 1000 # 模擬每次傳輸數據的大小為1000 30 try: # 處理StopIteration異常 31 progress.send(received_size) # 給progress發送最新received_size 32 except StopIteration as e: 33 print(‘100%‘)
#################################################################################################100% # 結果演示
用 python 的生成器制作數據傳輸進度條