Jupyter运行prompt_toolkit代码报RuntimeError:事件循环已运行的解决方法
解决Jupyter中prompt_toolkit的RuntimeError问题
我写了一个带自动补全的水果价格查询脚本,用prompt_toolkit实现,在VS Code里运行正常,但在Jupyter环境执行时总是报错:RuntimeError: This event loop is already running,需要解决这个问题。
原代码
from prompt_toolkit import prompt from prompt_toolkit.completion import WordCompleter # 水果价格字典 fruits = { "apple": 2.5, "orange": 3.0, "pinapple": 5.0, "banana": 1.5, "kiwi": 4.0, "mango": 6.0 } # 创建水果补全器 fruits_completer = WordCompleter(list(fruits.keys())) # 提示用户输入水果名称 fruit_input = prompt("Type the name of the fruit: ", completer=fruits_completer) # 显示所选水果的价格 price = fruits.get(fruit_input) if price: print(f"The price of the {fruit_input} is: {price}") else: print("The fruit is not in the list")
注:原代码存在变量名错误,已修正fruits变量覆盖问题
错误原因
Jupyter Notebook/Lab本身已经启动了一个异步事件循环,而prompt_toolkit的prompt()函数默认会尝试创建新的事件循环,导致循环冲突,触发上述错误。
解决方法
方案一:使用异步版本prompt配合Jupyter事件循环
利用prompt_toolkit的prompt_async()异步函数,通过Jupyter现有事件循环运行:
import asyncio from prompt_toolkit import prompt_async from prompt_toolkit.completion import WordCompleter fruits = { "apple": 2.5, "orange": 3.0, "pinapple": 5.0, "banana": 1.5, "kiwi": 4.0, "mango": 6.0 } fruits_completer = WordCompleter(list(fruits.keys())) async def get_fruit_price(): fruit_input = await prompt_async("Type the name of the fruit: ", completer=fruits_completer) price = fruits.get(fruit_input) if price: print(f"The price of the {fruit_input} is: {price}") else: print("The fruit is not in the list") # 在Jupyter现有事件循环中运行 asyncio.create_task(get_fruit_price())
方案二:使用nest_asyncio允许嵌套事件循环
安装nest_asyncio库后,让Jupyter支持嵌套事件循环,原代码可直接运行:
- 安装依赖库:
pip install nest_asyncio
- 修改后的代码:
import nest_asyncio from prompt_toolkit import prompt from prompt_toolkit.completion import WordCompleter # 允许嵌套事件循环 nest_asyncio.apply() fruits = { "apple": 2.5, "orange": 3.0, "pinapple": 5.0, "banana": 1.5, "kiwi": 4.0, "mango": 6.0 } fruits_completer = WordCompleter(list(fruits.keys())) fruit_input = prompt("Type the name of the fruit: ", completer=fruits_completer) price = fruits.get(fruit_input) if price: print(f"The price of the {fruit_input} is: {price}") else: print("The fruit is not in the list")
预期运行效果
运行后提示输入水果名称,输入前缀如app时会弹出apple补全选项,选择回车后显示对应价格:
Type the name of the fruit: app Type the name of the fruit: apple The price of the apple is: 2.5
内容的提问来源于stack exchange,提问作者Javier
相关产品推荐
相关产品推荐

