-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcoroutines01.py
61 lines (36 loc) · 1.18 KB
/
coroutines01.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
"""使用协程实现的一个图形化下载器,原理很简单,就是将任务切片,交替执行
比较初级,算是学习协程的一个小练习吧
"""
import requests
import sys
def download(url, ):
response = requests.get(url, stream=True)
size = int(response.headers['content-length'])
now_size = 0
with open('test.mp4', 'wb') as f:
for data in response.iter_content(chunk_size=1024):
f.write(data)
now_size += len(data)
x = yield float(now_size/size)
def draw():
while True:
percentage = yield
sys.stdout.write('\r')
sys.stdout.write('正在下载 ' + '#' * int(20 * percentage))
sys.stdout.flush()
def main():
url = 'http://vod1oowvkrz.nosdn.127.net/574931449-192281719157761.mp4'
download_machine = download(url)
draw_machine = draw()
next(download_machine)
next(draw_machine)
while True:
try:
percentage = download_machine.send(1)
except StopIteration:
sys.stdout.write('\r下载成功')
break
else:
draw_machine.send(percentage)
if __name__ == '__main__':
main()