# _*_ coding: utf-8 _*_"""python_coroutine.py by xianhu"""import asyncioimport aiohttpimport threading# 生产者、消费者例子def consumer(): # 定义消费者,由于有yeild关键词,此消费者为一个生成器print("[Consumer] Init Consumer ......")r = "init ok" # 初始化返回结果,并在启动消费者时,返回给生产者while True:n = yield r # 消费者通过yield关键词接收生产者产生的消息,同时返回结果给生产者print("[Consumer] conusme n = %s, r = %s" % (n, r))r = "consume %s OK" % n # 消费者消费结果,下个循环返回给生产者def produce(c): # 定义生产者,此时的 c 为一个生成器print("[Producer] Init Producer ......")r = c.send(None) # 启动消费者生成器,同时第一次接收返回结果print("[Producer] Start Consumer, return %s" % r)n = 0while n < 5:n += 1print("[Producer] While, Producing %s ......" % n)r = c.send(n) # 向消费者发送消息,同时准备接收结果。此时会切换到消费者执行print("[Producer] Consumer return: %s" % r)c.close() # 关闭消费者生成器print("[Producer] Close Producer ......")# produce(consumer())# 异步IO例子:适配Python3.4,使用asyncio库@asyncio.coroutinedef hello(index): # 通过装饰器asyncio.coroutine定义协程print('Hello world! index=%s, thread=%s' % (index, threading.currentThread()))yield from asyncio.sleep(1) # 模拟IO任务print('Hello again! index=%s, thread=%s' % (index, threading.currentThread()))@asyncio.coroutineloop = asyncio.get_event_loop() # 得到一个事件循环模型tasks = [hello(1), hello(2)] # 初始化任务列表loop.run_until_complete(asyncio.wait(tasks)) # 执行任务loop.close() # 关闭事件循环列表# 异步IO例子:适配Python3.5,使用async和await关键字async def hello1(index): # 通过关键字async定义协程print('Hello world! index=%s, thread=%s' % (index, threading.currentThread()))await asyncio.sleep(1) # 模拟IO任务print('Hello again! index=%s, thread=%s' % (index, threading.currentThread()))loop = asyncio.get_event_loop() # 得到一个事件循环模型tasks = [hello1(1), hello1(2)] # 初始化任务列表loop.run_until_complete(asyncio.wait(tasks)) # 执行任务loop.close() # 关闭事件循环列表# aiohttp 实例async def get(url):async with aiohttp.ClientSession() as session:async with session.get(url) as resp:print(url, resp.status)print(url, await resp.text())loop = asyncio.get_event_loop() # 得到一个事件循环模型tasks = [ # 初始化任务列表get("http://zhushou.360.cn/detail/index/soft_id/3283370"),get("http://zhushou.360.cn/detail/index/soft_id/3264775"),get("http://zhushou.360.cn/detail/index/soft_id/705490")]loop.run_until_complete(asyncio.wait(tasks)) # 执行任务loop.close() # 关闭事件循环列表
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。