Skip to content

Commit c2de969

Browse files
committed
add python_coroutine.py
1 parent 84c3342 commit c2de969

File tree

2 files changed

+81
-2
lines changed

2 files changed

+81
-2
lines changed

README.md

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
# LearnPython
22
以撸代码的形式学习Python, 具体说明在[知乎专栏-撸代码,学知识](https://zhuanlan.zhihu.com/pythoner)
33

4-
===============================================================================
4+
===================================================================================================
55
### python_base.py: 千行代码入门Python
66

77
### python_visual.py: 15张图入门Matplotlib
@@ -25,6 +25,8 @@
2525
### python_datetime.py: 你真的了解Python中的日期时间处理吗?
2626

2727
### python_metaclass.py: Python进阶: 一步步理解Python中的元类metaclass
28-
===============================================================================
28+
29+
### python_coroutine.py: Python进阶:理解Python中的异步IO和协程(Coroutine), 并应用在爬虫中
30+
===================================================================================================
2931

3032
### 您可以fork该项目,并在修改后提交Pull request

python_coroutine.py

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
# _*_ coding: utf-8 _*_
2+
3+
"""
4+
python_coroutine.py by xianhu
5+
"""
6+
7+
import asyncio
8+
import aiohttp
9+
import threading
10+
11+
12+
# 生产者、消费者例子
13+
def consumer(): # 定义消费者,由于有yeild关键词,此消费者为一个生成器
14+
print("[Consumer] Init Consumer ......")
15+
r = "init ok" # 初始化返回结果,并在启动消费者时,返回给生产者
16+
while True:
17+
n = yield r # 消费者通过yield关键词接收生产者产生的消息,同时返回结果给生产者
18+
print("[Consumer] conusme n = %s, r = %s" % (n, r))
19+
r = "consume %s OK" % n # 消费者消费结果,下个循环返回给生产者
20+
21+
22+
def produce(c): # 定义生产者,此时的 c 为一个生成器
23+
print("[Producer] Init Producer ......")
24+
r = c.send(None) # 启动消费者生成器,同时第一次接收返回结果
25+
print("[Producer] Start Consumer, return %s" % r)
26+
n = 0
27+
while n < 5:
28+
n += 1
29+
print("[Producer] While, Producing %s ......" % n)
30+
r = c.send(n) # 向消费者发送消息,同时准备接收结果。此时会切换到消费者执行
31+
print("[Producer] Consumer return: %s" % r)
32+
c.close() # 关闭消费者生成器
33+
print("[Producer] Close Producer ......")
34+
35+
# produce(consumer())
36+
37+
38+
# 异步IO例子:适配Python3.4,使用asyncio库
39+
@asyncio.coroutine
40+
def hello(index): # 通过装饰器asyncio.coroutine定义协程
41+
print('Hello world! index=%s, thread=%s' % (index, threading.currentThread()))
42+
yield from asyncio.sleep(1) # 模拟IO任务
43+
print('Hello again! index=%s, thread=%s' % (index, threading.currentThread()))@asyncio.coroutine
44+
45+
loop = asyncio.get_event_loop() # 得到一个事件循环模型
46+
tasks = [hello(1), hello(2)] # 初始化任务列表
47+
loop.run_until_complete(asyncio.wait(tasks)) # 执行任务
48+
loop.close() # 关闭事件循环列表
49+
50+
51+
# 异步IO例子:适配Python3.5,使用async和await关键字
52+
async def hello1(index): # 通过关键字async定义协程
53+
print('Hello world! index=%s, thread=%s' % (index, threading.currentThread()))
54+
await asyncio.sleep(1) # 模拟IO任务
55+
print('Hello again! index=%s, thread=%s' % (index, threading.currentThread()))
56+
57+
loop = asyncio.get_event_loop() # 得到一个事件循环模型
58+
tasks = [hello1(1), hello1(2)] # 初始化任务列表
59+
loop.run_until_complete(asyncio.wait(tasks)) # 执行任务
60+
loop.close() # 关闭事件循环列表
61+
62+
63+
# aiohttp 实例
64+
async def get(url):
65+
async with aiohttp.ClientSession() as session:
66+
async with session.get(url) as resp:
67+
print(url, resp.status)
68+
print(url, await resp.text())
69+
70+
loop = asyncio.get_event_loop() # 得到一个事件循环模型
71+
tasks = [ # 初始化任务列表
72+
get("http://zhushou.360.cn/detail/index/soft_id/3283370"),
73+
get("http://zhushou.360.cn/detail/index/soft_id/3264775"),
74+
get("http://zhushou.360.cn/detail/index/soft_id/705490")
75+
]
76+
loop.run_until_complete(asyncio.wait(tasks)) # 执行任务
77+
loop.close() # 关闭事件循环列表

0 commit comments

Comments
 (0)