VSCode Notebook中Python lightweight_charts遇asyncio事件循环错误求助
解决VSCode Notebook中lightweight_charts的asyncio事件循环冲突问题
方案一:使用nest_asyncio允许嵌套事件循环
这是最直接的解决方法,Notebook本身运行在asyncio事件循环中,而chart.show(block=True)内部调用asyncio.run()会触发循环冲突,nest_asyncio可允许Python嵌套运行事件循环。
- 安装依赖:
pip install nest_asyncio
- 修改代码添加初始化逻辑:
from ipynb.fs.full.tool_read_db import get_table2df_pastdays from lightweight_charts import Chart import nest_asyncio # 启用嵌套事件循环支持 nest_asyncio.apply() table = get_table2df_pastdays('BTCUSDTBB5m',10,1) table.rename(columns={'openDateTime':'date'},inplace=True) chart = Chart() chart.set(table) # 直接传入DataFrame即可,无需使用iloc索引器 chart.show(block=True)
方案二:直接利用现有事件循环运行异步逻辑
若不想额外安装库,可直接调用lightweight_charts的异步显示接口(若版本支持),或手动在现有循环中启动任务:
from ipynb.fs.full.tool_read_db import get_table2df_pastdays from lightweight_charts import Chart import asyncio table = get_table2df_pastdays('BTCUSDTBB5m',10,1) table.rename(columns={'openDateTime':'date'},inplace=True) chart = Chart() chart.set(table) # 在Notebook的现有事件循环中启动图表显示 asyncio.create_task(chart.show_async())
注:部分旧版本lightweight_charts可能无show_async方法,此时方案一更稳妥。
问题原因
VSCode/Jupyter Notebook本身基于asyncio事件循环运行,chart.show(block=True)内部会调用asyncio.run()启动新的事件循环,而asyncio规则禁止在已有运行的循环中重复调用asyncio.run(),因此触发RuntimeError。
内容的提问来源于stack exchange,提问作者Mike vanDerBar
相关产品推荐
相关产品推荐

