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 回答。