python学习

(技术)Python 3 -- 异步IO: asyncio

2017-11-24  本文已影响0人  点映文艺

先上代码


#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 注意 文件不要命名为"asyncio.py" 否则会报错  AttributeError: module 'asyncio' has no attribute 'coroutine'
import asyncio

@asyncio.coroutine   #把一个generator(生成器)标记为coroutine类型,就是所谓的协程
def say_hello():
    print('Hello,asyncio !!!')
    # 异步调用asyncio.sleep(1):
    r = yield from asyncio.sleep(1)
    print('Hello,again')

# 获取EventLoop
loop = asyncio.get_event_loop();
#将generator(协程)丢进EventLoop中执行
loop.run_until_complete(say_hello())
loop.close()

Coroutine 翻译一下:协同程序 ,简意为协程,又称微线程

@asyncio.coroutine → 把一个generator(生成器)标记为coroutine类型,就是所谓的协程

asyncio的实质核心就是一个消息循环。从asyncio模块中获取一个EventLoop的引用,把需要执行的Coroutine(协程)扔到
EventLoop中执行,就实现了异步IO。注意,执行完了记得要close关闭。

说说async/await, async和await是Python 3.5新引入的语法,目的是让coroutine(协程)的代码更简洁易读

上代码

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 注意 文件不要命名为"asyncio.py" 否则会报错  AttributeError: module 'asyncio' has no attribute 'coroutine'
import asyncio

async def say_hello():  #把一个generator(生成器)标记为coroutine类型,就是所谓的协程
    print('Hello,asyncio !!!')
    # 异步调用asyncio.sleep(1):
    r = await asyncio.sleep(1)
    print('Hello,again')

# 获取EventLoop
loop = asyncio.get_event_loop();
#将generator(协程)丢进EventLoop中执行
loop.run_until_complete(say_hello())
loop.close()

核心要点:  1、把@asyncio.coroutine替换为async;
                    2、把yield from替换为await。

上一篇下一篇

猜你喜欢

热点阅读