可以仅运行asyncio事件循环的一个步骤 [英] Is it possible to run only a single step of the asyncio event loop
问题描述
@ asyncio.coroutine
def run_tk(tk,interval = 0.1):
try:
while True:
tk.update()
从asyncio.sleep间隔)
除了TclError作为e:
如果应用程序已被销毁不在e.args [0]:
raise
但是,为了探索所有选项,我想知道是否可以做相反的事情 - 如果可以仅调用asyncio的单个迭代
缺少公共方法,如 loop.run_once()
是有意的。
不是每个支持的事件循环都有迭代一步的方法。通常底层API有创建事件循环和运行它的方法,但是模拟单步可能非常无效。
如果真的需要它,您可以实现单步迭代:
导入asyncio
def run_once(循环):
循环.call_soon(loop.stop)
loop.run_forever()
loop = asyncio.get_event_loop()
适用于范围(100) :
print('Iteration',i)
run_once(loop)
I'm working on a simple graphical network application, using asyncio and tkinter. I'm running into the problem of combining the asyncio event loop with Tk's mainloop. If possible, I'd like to do it without threads, because both these libraries (but especially tkinter) aren't very thread safe. Currently, I'm using Tk.update in an asyncio coroutine, which runs only a single 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 options, I was wondering if it was possible to do the reverse- if it was possible to invoke only a single iteration of an asyncio event loop inside a tk callback.
The missing of public method like loop.run_once()
is intentional.
Not every supported event loop has method to iterate one step. Often underlying API has methods for creating event loop and running it forever but emulating single step may be very ineffective.
If you really need it you may implement single-step iteration easy:
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)
这篇关于可以仅运行asyncio事件循环的一个步骤的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!