You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于prompt_toolkit的全屏终端聊天应用添加确认弹窗遇事件循环冲突

解决prompt_toolkit事件循环冲突的退出确认弹窗问题

我基于prompt_toolkit开发终端聊天应用,通过继承Application实现了全屏布局的Dashboard,并在消息框中加入命令处理逻辑。触发exit/quit/q命令时,想添加官方文档里的确认弹窗,但每次都会抛出Exception This event loop is already running异常——原因很明显,Dashboard已经在运行事件循环,无法嵌套启动新的事件循环。

解决方案

不要使用会启动新事件循环的同步弹窗方法,而是利用prompt_toolkit现有事件循环,通过异步任务来处理确认逻辑。以下是修改后的代码示例:

from prompt_toolkit.shortcuts import confirm

# 原Dashboard类的process_message方法中,exit分支替换为:
elif buffer in ['exit', 'quit', 'q']:
    async def confirm_and_exit():
        # 异步调用确认弹窗,不会启动新循环
        user_confirmed = await confirm("确定要退出吗?")
        if user_confirmed:
            self.exit()
    
    # 将异步任务加入Application的现有事件循环
    self.create_task(confirm_and_exit())

原理说明

prompt_toolkit的Application实例运行时已经维护了一个事件循环,直接调用confirm()这类同步方法会尝试启动新循环,导致冲突。改用异步版本的await confirm(...),并通过self.create_task()将任务提交到现有循环中执行,就能避免嵌套循环的问题,同时实现退出确认的交互。

内容的提问来源于stack exchange,提问作者JRudransh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 18:35:50