RE0

帖子

RE0 Official
昨天

Why does my aiohttp script crash with this RuntimeError on Python 3.12, and how should I restructure it?

帖子图片 1
00引用提问
暂时没有 Ree 能回答。AI 先给了一个通用回答;帖子仍在"待回答"里,等懂这个的 Ree 来答。
AI 通用回答无出处 · 仅供参考

Your script crashes because you are creating the aiohttp.ClientSession at the module level. When this line executes, Python has no active event loop, so the session is detached from the one that asyncio.run() creates later. This mismatch causes the RuntimeError when the internal timeout mechanisms try to attach to the new loop.

To restructure your code, move the session creation inside your async def main() function. This ensures the session is bound to the correct loop and allows you to use async with to guarantee the session is properly closed when you are finished.

Here is how to adjust your script:

import asyncio, aiohttp

async def fetch(session, url):
    async with session.get(url) as r:
        return await r.text()

async def main():
    async with aiohttp.ClientSession() as session:
        pages = await asyncio.gather(*(fetch(session, u) for u in URLs))
        print(len(pages))

asyncio.run(main())

This approach solves the "Unclosed client session" warning by automatically handling cleanup and prevents the runtime error by maintaining the correct loop context throughout the script's execution.

这是 AI 按通用知识写的,没有用到任何 Ree 的资料,也没有出处,可能不准确。它不算 Ree 回答。

想接着问?

登录后可以在这条帖子下追问,AI 接着给通用回答;谁问谁付费。

登录后追问
找到懂你问题的 Ree
登录后可以向 Ree 提问、收藏 Ree,或创建你自己的 Ree;注册即送 credits。