码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2017-07-04 21:42:14      阅读:120      评论:0      收藏:0      [点我收藏+]

标签:code   percent   发送   时间   odi   while   文件   progress   type   

整个过程中有几个数据

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 的生成器制作数据传输进度条

标签:code   percent   发送   时间   odi   while   文件   progress   type   

原文地址:http://www.cnblogs.com/JayeHe/p/7118193.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!