aiomultiprocess

0.9.1 · active · verified Thu Apr 09

aiomultiprocess is a Python library that provides an asynchronous version of the standard `multiprocessing` module, combining the benefits of `asyncio` for I/O-bound tasks and `multiprocessing` for CPU-bound tasks. It runs a full `asyncio` event loop on each child process, enabling high levels of concurrency and parallelism beyond the Global Interpreter Lock (GIL). The library is actively maintained, with its current version being 0.9.1.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates using `aiomultiprocess.Pool` to fetch multiple URLs concurrently across several processes. It defines an asynchronous function `fetch_url_content` that uses `aiohttp` to make an HTTP GET request. The `main` function then creates a `Pool` and uses its `map` method to distribute the `fetch_url_content` coroutine calls across the worker processes, iterating over results as they complete.

import asyncio
from aiohttp import ClientSession
from aiomultiprocess import Pool

async def fetch_url_content(url: str) -> str:
    """An example async coroutine to be run by the pool."""
    async with ClientSession() as session:
        async with session.get(url) as response:
            response.raise_for_status() # Raise an exception for bad status codes
            return await response.text()

async def main():
    urls = [
        "https://www.google.com",
        "https://www.python.org",
        "https://docs.python.org/3/library/asyncio.html",
        "https://www.wikipedia.org"
    ]

    print(f"Fetching {len(urls)} URLs using aiomultiprocess Pool...")
    async with Pool(processes=2) as pool: # Use 2 processes for demonstration
        # Use pool.map to apply the coroutine to each URL
        async for result in pool.map(fetch_url_content, urls):
            if result: # Check if result is not None (e.g., if an exception was caught by handler)
                print(f"Fetched content size: {len(result)} bytes for one URL.")
            else:
                print("Failed to fetch content for a URL.")

if __name__ == '__main__':
    # Ensure aiohttp is installed for this example: pip install aiohttp
    try:
        asyncio.run(main())
    except ImportError:
        print("Please install aiohttp for this example: pip install aiohttp")
    except Exception as e:
        print(f"An error occurred: {e}")

view raw JSON →