Is it possible to run only one step of the asyncio event loop

I am working on a simple graphical network application using asyncio and tkinter. I ran into the problem of combining an asyncio event loop with Tk mainloop. If possible, I would like to do this without streams, because both of these libraries (but especially tkinter) are not very reliable in streaming mode. I am currently using Tk.update in asyncio coroutine, which only triggers one iteration of the tk event loop:

@asyncio.coroutine def run_tk(tk, interval=0.1): try: while True: tk.update() yield from asyncio.sleep(interval) except TclError as e: if "application has been destroyed" not in e.args[0]: raise 

However, in the interest of exploring all the parameters, I was wondering if the opposite could be done if it was possible to call only one iteration of the asyncio event loop inside the tk callback.

+7
python events tkinter tk python-asyncio
source share
1 answer

There is no public method like loop.run_once() . Not every supported event loop has a method for repeating one step. Often the core API has methods for creating an event loop and executing it forever, but emulating one step can be very inefficient.

If you really need it, you can easily do a one-step iteration:

 import asyncio def run_once(loop): loop.call_soon(loop.stop) loop.run_forever() loop = asyncio.get_event_loop() for i in range(100): print('Iteration', i) run_once(loop) 
+9
source share

All Articles