gpt4 book ai didi

python - 运行时错误 : Event loop is closed in asyncpraw python

转载 作者:行者123 更新时间:2023-12-04 15:04:28 24 4
gpt4 key购买 nike

我正在尝试使用 asyncpraw 库,但我得到了 RuntimeError: Event loop is closed

这是我的代码和回溯。

代码

import asyncio
import asyncpraw

async def main():
reddit = asyncpraw.Reddit('praw_ini_name')
print('User is', await reddit.user.me())
await reddit.close()

asyncio.run(main())

回溯

User is python_user
Exception ignored in: <function _ProactorBasePipeTransport.__del__ at 0x0000021D2898C1F0>
Traceback (most recent call last):
File "C:\Program Files\Python39\lib\asyncio\proactor_events.py", line 116, in __del__
self.close()
File "C:\Program Files\Python39\lib\asyncio\proactor_events.py", line 108, in close
self._loop.call_soon(self._call_connection_lost, None)
File "C:\Program Files\Python39\lib\asyncio\base_events.py", line 746, in call_soon
self._check_closed()
File "C:\Program Files\Python39\lib\asyncio\base_events.py", line 510, in _check_closed
raise RuntimeError('Event loop is closed')
RuntimeError: Event loop is closed

但是,如果我像这样启动事件循环,这不会发生(无一异常(exception))

import asyncio
import asyncpraw

async def main():
reddit = asyncpraw.Reddit('praw_ini_name')
print('User is', await reddit.user.me())
await reddit.close()

loop = asyncio.get_event_loop()
loop.run_until_complete(main())

我假设在较新的 python 版本中,启动事件循环的首选方式是我在第一个片段中显示的方式,那么为什么它不起作用?即使它打印了输出,为什么我的代码会抛出异常?

我使用的是 Python 3.9.2,asyncpraw 7.2.0。

我见过 Asyncio Event Loop is ClosedPython3.x RuntimeError: Event loop is closedAiohttp, Asyncio: RuntimeError: Event loop is closed 我相信他们不是骗子。我的问题是为什么它适用于一个而不适用于另一个。

如果我不使用 reddit.close() 我会得到以下信息

User is python_user
Unclosed client session
client_session: <aiohttp.client.ClientSession object at 0x0000025BAAAEF8B0>
Unclosed connector
connections: ['[(<aiohttp.client_proto.ResponseHandler object at 0x0000025BAAAF1640>, 174448.968)]']
connector: <aiohttp.connector.TCPConnector object at 0x0000025BAAAEFA90>

谢谢。

最佳答案

asyncio.run 在完成时明确关闭循环。

asyncio.run(coro, *, debug=False)

[...]
This function always creates a new event loop and closes it at the end.

这意味着一旦 main 完成,事件循环不可用于清理。必须通过 async generators 确定性地进行清理, 或同步。

当手动管理循环而不调用 loop.close() 时,循环仍可用于安排清理回调。请注意,这并不一定意味着清理实际上运行,除非显式恢复循环。


具体问题是known issue with aiohttp 3.x .

关于python - 运行时错误 : Event loop is closed in asyncpraw python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66412420/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com