可以仅运行asyncio事件循环的一个步骤 [英] Is it possible to run only a single step of the asyncio event loop

查看:674
本文介绍了可以仅运行asyncio事件循环的一个步骤的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用一个简单的图形网络应用程序,使用asyncio和tkinter。我遇到了将asyncio事件循环与Tk的mainloop组合在一起的问题。如果可能,我想做没有线程,因为这两个库(但特别是tkinter)不是很线程安全。目前,我在一个asyncio协程中使用Tk.update,它只运行tk事件循环的单次迭代:

  @ 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆