You need to enable JavaScript to run this app. Jupyter运行Twint时报RuntimeError: This event loop is already running问题
优惠活动
大模型
产品
解决方案
定价
更多

Jupyter运行Twint时报RuntimeError: This event loop is already running问题

错误原因

Jupyter Notebook 内核默认会启动一个常驻的异步事件循环,而 Twint 封装的同步运行接口(如twint.run.Followers)内部会尝试获取当前事件循环并调用run_until_complete()方法,asyncio 不允许在已经运行的事件循环上重复触发同步执行逻辑,因此抛出该RuntimeError。

解决方案

方案1:使用nest_asyncio适配嵌套事件循环(推荐,无需修改原有业务代码)

该方案通过补丁允许异步事件循环嵌套运行,直接兼容你原有的Twint调用逻辑:

  1. 安装依赖库:
    pip install nest_asyncio
  2. 在运行Twint代码前先执行补丁注入:
import nest_asyncio
nest_asyncio.apply()
  1. 直接运行你原有的Twint代码即可:
c = twint.Config()
c.Username = 'twitter'
c.Limit = 20
twint.run.Followers(c)

方案2:原生异步调用(无需额外安装依赖)

直接适配Jupyter已有的异步运行环境,用await调用Twint的异步逻辑:

import twint

c = twint.Config()
c.Username = 'twitter'
c.Limit = 20
# 开启异步运行配置
c.Run_Async = True

# 直接await执行任务,适配Jupyter已有的事件循环
await twint.run.Followers(c)

如果使用的Twint版本不支持Run_Async配置,可替换为直接调用核心协程:

await twint.Twint(c).main()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.20 02:45:01