coroutine in corso richiede un ciclo evento. Utilizzare il asyncio()
library per creare uno:
import asyncio
loop = asyncio.get_event_loop()
loop.run_until_complete(foo())
loop.close()
vedere anche la Tasks and Coroutines chapter of the asyncio
documentation.
Nota tuttavia che time.sleep()
è non un oggetto attendibile. Esso restituisce None
in modo da ottenere un'eccezione dopo 1 secondo:
>>> 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
si dovrebbe usare il asyncio.sleep()
coroutine invece:
async def foo():
await asyncio.sleep(1)
fonte
2015-09-27 14:25:00