python - Execute coroutine from `call_soon` callback function -


i have following situation:

  • some internal class (which have no control of) executing callback function using call_soon.
  • within callback call courotune, end "frozen" callback.

i use modified hello world call_soon() demonstrate this:

import asyncio  def hello_world(loop):     print('hello')     # call coroutine.     yield asyncio.sleep(5, loop=loop)     print('world')     loop.stop()  loop = asyncio.get_event_loop()  # schedule call hello_world() loop.call_soon(hello_world, loop)  # blocking call interrupted loop.stop() loop.run_forever() loop.close() 

when run this, nothing being printed , program never ends.

ctrl+c

traceback (most recent call last):   file "../soon.py", line 15, in <module>     loop.run_forever()   file "/usr/lib/python3.4/asyncio/base_events.py", line 276, in run_forever     self._run_once()   file "/usr/lib/python3.4/asyncio/base_events.py", line 1136, in _run_once     event_list = self._selector.select(timeout)   file "/usr/lib/python3.4/selectors.py", line 432, in select     fd_event_list = self._epoll.poll(timeout, max_ev) keyboardinterrupt 

what going on , why?

any correct way this?

the example mentioned demonstrate how schedule callback.

if use yield from syntax, function coroutine , has decorated accordingly:

@asyncio.coroutine def hello_world(loop):     print('hello')     yield asyncio.sleep(5, loop=loop)     print('world')     loop.stop() 

then can schedule coroutine task using ensure_future:

loop = asyncio.get_event_loop() coro = hello_world(loop) asyncio.ensure_future(coro) loop.run_forever() loop.close() 

or equivalently, using run_until_complete:

loop = asyncio.get_event_loop() coro = hello_world(loop) loop.run_until_complete(coro) 

in 2 weeks, python 3.5 officially released , you'll able use new async/await syntax:

async def hello_world(loop):     print('hello')     await asyncio.sleep(5, loop=loop)     print('world') 

edit: bit ugly, nothing prevents creating callback schedules 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() 

Comments

Popular posts from this blog

c# - Binding a comma separated list to a List<int> in asp.net web api -

Delphi 7 and decode UTF-8 base64 -

html - Is there any way to exclude a single element from the style? (Bootstrap) -