RuntimeError:asyncpraw python中的事件循环已关闭

2024-09-28 22:25:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图使用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

但是,如果像这样启动事件循环,则不会发生这种情况(没有例外)

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版本中,启动事件循环的首选方式是我在第一个代码段中显示的方式,那么为什么这不起作用呢?即使它打印输出,为什么我的代码会抛出异常

我使用的是Python3.9.2,带有asyncpraw7.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>

多谢各位


Tags: inimportloopeventasynciocloseismain
1条回答
网友
1楼 · 发布于 2024-09-28 22:25:52

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

相关问题 更多 >