【问题标题】:"async with" if the event loop is running but no event loop如果事件循环正在运行但没有事件循环,则为“异步”
【发布时间】:2020-06-10 09:52:08
【问题描述】:

我在尝试运行Telethon documentation 提供的基本代码时收到以下错误。我很困惑为什么我还没有建立一个循环。

RuntimeError: 如果事件循环正在运行,您必须使用“async with”(即您在“async def”中)

我在 spyder 4.0.1 中使用 python 3.7.7

from telethon.sync import TelegramClient
from telethon import functions, types

def channel_info(username, api_id, api_hash):
    with TelegramClient(username, api_id, api_hash,channel) as client:
        result = client(functions.channels.GetFullChannelRequest(
            channel=channel
        ))
        return(result)

out = channel_info(username, api_id, api_hash)

【问题讨论】:

  • > 因为我还没有建立循环。默认情况下,asyncio 在主线程上创建一个事件循环,Anaconda/Spyder/IPython 等工具会自动为您运行该循环,这使您可以直接在解释器中使用async withasync forawait .
  • 这是非常重要的一点。如果您是包的开发者,请在包文档中明确提及。

标签: python telegram telethon


【解决方案1】:

根据 Telethon 文档的 FAQ section

我可以在库中使用 Anaconda/Spyder/IPython 吗?

是的,但是这些 解释器隐式运行 asyncio 事件循环,这会干扰 使用 telethon.sync 魔术模块。如果你使用它们,你不应该 导入同步。

所以避免使用sync 模块。

您可以尝试这样做:

from telethon import TelegramClient, functions, types
from asyncio import run

API_ID= ...
API_HASH=" ... "

async def channel_info(username, api_id, api_hash):
    async with TelegramClient('session', api_id, api_hash) as client:
        result = await client(functions.channels.GetFullChannelRequest(
            channel=username
        ))
        return(result)


out = run(channel_info('durov', API_ID, API_HASH))
print(out)

【讨论】:

  • 我已经在 spyder 中尝试过你的代码。但它给出了这个错误:"asyncio.run() cannot be called from a running event loop") RuntimeError: asyncio.run() cannot be called from a running event loop
  • @jonny789 对我来说同样的错误。你找到正确的方法了吗?
  • @Ehsan,我不在 spyder 的 Ipython 控制台中运行。我在专用控制台中运行。转到Run > Configuration per file > 在Console 下选择Execute in a dedicated console
猜你喜欢
  • 2017-07-07
  • 2018-04-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-02-09
  • 1970-01-01
  • 2017-02-06
相关资源
最近更新 更多