The example you mentioned shows how to schedule a callback.
If you use yield from syntax, this function is actually coroutine , and it should be properly formatted:
@asyncio.coroutine def hello_world(loop): print('Hello') yield from asyncio.sleep(5, loop=loop) print('World') loop.stop()
Then you can schedule the coroutine as a task using ensure_future :
loop = asyncio.get_event_loop() coro = hello_world(loop) asyncio.ensure_future(coro) loop.run_forever() loop.close()
Or, which is the same using run_until_complete :
loop = asyncio.get_event_loop() coro = hello_world(loop) loop.run_until_complete(coro)
In two weeks, python 3.5 will be officially released and you can use the new async / await syntax:
async def hello_world(loop): print('Hello') await asyncio.sleep(5, loop=loop) print('World')
EDIT . This is a little ugly, but nothing prevents you from creating a callback that plans your coroutine:
loop = asyncio.get_event_loop() coro = hello_world(loop) callback = lambda: asyncio.ensure_future(coro) loop.call_soon(callback) loop.run_forever() loop.close()
Vincent
source share