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

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

问题描述

我正在使用 asyncio 和 tkinter 开发一个简单的图形网络应用程序.我遇到了将 asyncio 事件循环与 Tk 的主循环相结合的问题.如果可能的话,我想在没有线程的情况下进行,因为这两个库(尤其是 tkinter)都不是线程安全的.目前,我在 asyncio 协程中使用 Tk.update,它只运行 tk 事件循环的一次迭代:

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

然而,为了探索所有选项,我想知道是否可以反向执行 - 是否可以在 tk 回调中仅调用一次异步事件循环.

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.

推荐答案

缺少像 loop.run_once() 这样的公共方法是故意的.并非每个受支持的事件循环都有迭代一个步骤的方法.通常底层 API 具有创建事件循环并永远运行它的方法,但模拟单步可能非常无效.

The missing of public method like loop.run_once() is intentional. Not every supported event loop has a 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天全站免登陆