异步函数python 异步函数有哪些( 四 )


我们都知道Python由于GIL(Global Interpreter Lock)原因,其线程效率并不高,并且在*nix系统中,创建线程的开销并不比进程小,因此在并发操作时 , 多线程的效率还是受到了很大制约的 。所以后来人们发现通过yield来中断代码片段的执行,同时交出了cpu的使用权,于是协程的概念产生了 。在Python3.4正式引入了协程的概念,代码示例如下:
import asyncio# Borrowed fromcountdown(number, n):
while n0:
print('T-minus', n, '({})'.format(number))yield from asyncio.sleep(1)
n -= 1loop = asyncio.get_event_loop()
tasks = [
asyncio.ensure_future(countdown("A", 2)),
asyncio.ensure_future(countdown("B", 3))]
loop.run_until_complete(asyncio.wait(tasks))
loop.close()12345678910111213141516
示例显示了在Python3.4引入两个重要概念协程和事件循环,
通过修饰符@asyncio.coroutine定义了一个协程,而通过event loop来执行tasks中所有的协程任务 。之后在Python3.5引入了新的asyncawait语法,从而有了原生协程的概念 。
asyncawait
在Python3.5中,引入了ayncawait 语法结构,通过”aync def”可以定义一个协程代码片段,作用类似于Python3.4中的@asyncio.coroutine修饰符,而await则相当于”yield from” 。
先来看一段代码,这个是我刚开始使用asyncawait语法时,写的一段小程序 。
#!/usr/bin/env python# encoding:utf-8import asyncioimport requestsimport time
async def wait_download(url):
response = await requets.get(url)
print("get {} response complete.".format(url))
async def main():
start = time.time()
await asyncio.wait([
wait_download(""),
wait_download(""),
wait_download("")])
end = time.time()
print("Complete in {} seconds".format(end - start))
loop = asyncio.get_event_loop()
loop.run_until_complete(main())12345678910111213141516171819202122232425
这里会收到这样的报错:
Task exception was never retrieved
future: Task finished coro=wait_download() done, defined at asynctest.py:9 exception=TypeError("object Response can't be used in 'await' expression",)
Traceback (most recent call last):
File "asynctest.py", line 10, in wait_download
data = https://www.04ip.com/post/await requests.get(url)
TypeError: object Response can't be used in 'await' expression123456
这是由于requests.get()函数返回的Response对象不能用于await表达式,可是如果不能用于await,还怎么样来实现异步呢?
原来Python的await表达式是类似于”yield from”的东西 , 但是await会去做参数检查,它要求await表达式中的对象必须是awaitable的,那啥是awaitable呢? awaitable对象必须满足如下条件中其中之一:
1、A native coroutine object returned from a native coroutine function .
原生协程对象
2、A generator-based coroutine object returned from a function decorated with types.coroutine() .
types.coroutine()修饰的基于生成器的协程对象,注意不是Python3.4中asyncio.coroutine
3、An object with an await method returning an iterator.
实现了await method , 并在其中返回了iterator的对象
根据这些条件定义,我们可以修改代码如下:
#!/usr/bin/env python# encoding:utf-8import asyncioimport requestsimport time
async def download(url): # 通过async def定义的函数是原生的协程对象
response = requests.get(url)
print(response.text)
async def wait_download(url):
await download(url) # 这里download(url)就是一个原生的协程对象
print("get {} data complete.".format(url))
async def main():
start = time.time()
await asyncio.wait([
wait_download(""),
wait_download(""),
wait_download("")])
end = time.time()

推荐阅读