用 python 的生成器制作数据传输进度条

整个过程中有几个数据

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%      # 结果演示

 

posted on 2017-07-04 19:30  JayeHe  阅读(656)  评论(0编辑  收藏  举报

导航