Gevent

25.9.1 · active · verified Sat Mar 28

Gevent is a coroutine-based Python networking library that uses greenlet to provide a high-level synchronous API on top of the libev or libuv event loop. It enables writing concurrent code that looks sequential, primarily for I/O-bound tasks. The current version is 25.9.1, and it follows a CalVer (YY.0M.Micro) release cadence, aiming for at least monthly releases if changes are present in master.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates the core usage of Gevent: first, it applies monkey patching to make standard library functions cooperative. Then, it spawns multiple greenlets to perform I/O-bound tasks (fetching URLs) concurrently, and finally, it waits for all of them to complete.

from gevent import monkey; monkey.patch_all()
import gevent
import requests

def fetch_url(url):
    print(f"Fetching {url}...")
    try:
        response = requests.get(url, timeout=5) # requests uses patched socket
        print(f"Finished fetching {url}, status: {response.status_code}")
        return len(response.content)
    except requests.exceptions.RequestException as e:
        print(f"Error fetching {url}: {e}")
        return 0

urls = [
    "https://www.google.com",
    "https://www.github.com",
    "https://www.python.org"
]

# Spawn greenlets for each URL fetch
greenlets = [gevent.spawn(fetch_url, url) for url in urls]

# Wait for all greenlets to complete
gevent.joinall(greenlets)

total_bytes = sum(g.value for g in greenlets if g.successful())
print(f"Total bytes fetched: {total_bytes}")

view raw JSON →