如何使用aiomultiprocess?示例代码运行异常及触发方法求助
Hey there! Let's get your aiomultiprocess code working and fix that coroutine warning. Here's what's going wrong and how to fix it:
1. The "coroutine was never awaited" Warning
That error pops up because you're calling main() directly, but async functions (coroutines) can't run on their own—they need an asyncio event loop to execute them. The standard way to launch your async main function is using asyncio.run().
2. Corrected aiomultiprocess Code
Your core logic for using Pool and map() is on the right track, but we need to wrap everything properly to trigger execution. Here's the full working version:
import asyncio from aiohttp import request from aiomultiprocess import Pool async def get(url): async with request("GET", url) as response: return await response.text("utf-8") async def main(): urls = ["https://jreese.sh", "https://www.google.com"] async with Pool() as pool: # Iterate over the results returned by pool.map() async for result in pool.map(get, urls): # Truncate output to keep it readable print(f"Response snippet:\n{result[:100]}\n---") # Critical: Run the async main function with asyncio's event loop if __name__ == "__main__": asyncio.run(main())
Important Details:
- We added
import asyncioand wrapped the call tomain()withasyncio.run()inside anif __name__ == "__main__":block. This guard is essential for multiprocessing on Windows to prevent infinite process spawning. - The
Poolcontext manager handles creating and cleaning up processes for you, andpool.map()distributes yourgetcoroutine across multiple processes to run requests in parallel. - I added truncation to the output (
result[:100]) to avoid flooding your console with full HTML responses, but you can remove that if you want the complete text.
Why Your Original Code Did Nothing
Without asyncio.run(main()), your main() coroutine was never actually scheduled to run. No requests were sent, so there was no output—and the warning was the system telling you exactly what was missing!
内容的提问来源于stack exchange,提问作者Pranab

