如何在Python 3.5中使用async / await?

#!/usr/bin/env python3 # -*- coding: utf-8 -*- import time async def foo(): await time.sleep(1) foo() 

我不能让这个简单的例子来运行:

 RuntimeWarning: coroutine 'foo' was never awaited foo() 

运行协程需要一个事件循环 。 使用asyncio()库来创build一个:

 import asyncio loop = asyncio.get_event_loop() loop.run_until_complete(foo()) loop.close() 

另请参阅asyncio文档的“ 任务和协程”一章 。

请注意,time.sleep time.sleep() 不是一个等待对象。 它返回None所以你1秒后得到一个exception:

 >>> loop.run_until_complete(foo()) Traceback (most recent call last): File "<stdin>", line 1, in <module> File "/Users/mj/Development/Library/buildout.python/parts/opt/lib/python3.5/asyncio/base_events.py", line 342, in run_until_complete return future.result() File "/Users/mj/Development/Library/buildout.python/parts/opt/lib/python3.5/asyncio/futures.py", line 274, in result raise self._exception File "/Users/mj/Development/Library/buildout.python/parts/opt/lib/python3.5/asyncio/tasks.py", line 239, in _step result = coro.send(value) File "<stdin>", line 2, in foo TypeError: object NoneType can't be used in 'await' expression 

您应该使用asyncio.sleep()协程来代替:

 async def foo(): await asyncio.sleep(1)