python3.5怎么使用-如何在Python 3.5中使用async/await?

运行协同程序需要事件循环。使用

asyncio() library创建一个:

import asyncio

loop = asyncio.get_event_loop()

loop.run_until_complete(foo())

loop.close()

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

>>> loop.run_until_complete(foo())

Traceback (most recent call last):

File "", line 1, in

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 "", line 2, in foo

TypeError: object NoneType can't be used in 'await' expression

async def foo():

await asyncio.sleep(1)