#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import time
async def foo():
await time.sleep(1)
foo()
I couldn't make this dead simple example to run:
RuntimeWarning: coroutine 'foo' was never awaited foo()
解决方案
Running coroutines requires an event loop. Use the asyncio() library to create one:
import asyncio
loop = asyncio.get_event_loop()
loop.run_until_complete(foo())
loop.close()
Note however that time.sleep() is not an awaitable object. It returns None so you get an exception after 1 second:
>>> 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
You should use the asyncio.sleep() coroutine instead:
async def foo():
await asyncio.sleep(1)