我试图使用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,带有asyncpraw
7.2.0
我见过Asyncio Event Loop is Closed、Python3.x RuntimeError: Event loop is closed和Aiohttp, 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
明确性在完成时关闭循环这意味着一旦
main
完成,事件循环就不可用于清理。相反,必须通过async generators确定地或同步地进行清理当手动管理循环而不调用
loop.close()
时,循环仍然可以用于计划清除回调。请注意,这并不一定意味着清除实际上是运行,除非循环显式恢复具体的问题是known issue with aiohttp 3.x
相关问题 更多 >
编程相关推荐