python's asyncio recipes
- User
python's asyncio recipes
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
python's asyncio recipes
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Of course! Here is a collection of Python asyncio recipes, ranging from basic patterns to more advanced use cases. Each recipe is a self-contained, runnable example that demonstrates a specific concept.
asyncio.gatherasyncio.wait_forasyncio.waitrequests, file I/O)asyncio.Semaphoreasyncio.Queueasyncio.Eventasyncio.create_subprocess_shellThis is the "Hello, World!" of asyncio. It shows how to define an async function (a coroutine) and run it.
Concept: async def defines a coroutine. await pauses the coroutine to allow other tasks to run. asyncio.run() is the main entry point to start an asyncio program.
import asyncio
import time
# Define a coroutine function
async def say_after(delay, what):
"""A coroutine that waits for a given delay and then prints a message."""
print(f"[{time.strftime('%X')}] Started sleeping for {delay} second(s)...")
await asyncio.sleep(delay) # Non-blocking sleep
print(f"[{time.strftime('%X')}] {what}")
async def main():
"""The main entry point for our async program."""
print(f"[{time.strftime('%X')}] --- Program started ---")
# 'await' runs the coroutine and waits for it to complete.
await say_after(1, 'hello')
await say_after(2, 'world')
print(f"[{time.strftime('%X')}] --- Program finished ---")
# The modern way to run the main coroutine
if __name__ == "__main__":
asyncio.run(main())
Output:
[10:30:00] --- Program started ---
[10:30:00] Started sleeping for 1 second(s)...
[10:30:01] hello
[10:30:01] Started sleeping for 2 second(s)...
[10:30:03] world
[10:30:03] --- Program finished ---
asyncio.gatherThis is the most common pattern for running multiple asynchronous operations at the same time and waiting for all of them to finish.
Concept: asyncio.create_task() schedules a coroutine to run on the event loop soon. asyncio.gather() takes multiple awaitables (like tasks) and waits for all of them to complete, returning their results in order.
import asyncio
import time
async def say_after(delay, what):
await asyncio.sleep(delay)
print(f"[{time.strftime('%X')}] {what}")
return f"Returned: {what.upper()}"
async def main():
print(f"[{time.strftime('%X')}] --- Program started ---")
# Create tasks to run concurrently
task1 = asyncio.create_task(say_after(1, 'hello'))
task2 = asyncio.create_task(say_after(2, 'world'))
# Wait for both tasks to complete using asyncio.gather
# The total time will be ~2 seconds, not 1+2=3 seconds.
results = await asyncio.gather(task1, task2)
print(f"[{time.strftime('%X')}] --- Program finished ---")
print("Results from gather:", results)
if __name__ == "__main__":
asyncio.run(main())
Output:
[10:32:15] --- Program started ---
[10:32:16] hello
[10:32:17] world
[10:32:17] --- Program finished ---
Results from gather: ['Returned: HELLO', 'Returned: WORLD']
asyncio.wait_forEssential for making your application resilient. This prevents a single slow operation from blocking your entire program indefinitely.
Concept: asyncio.wait_for() wraps an awaitable and raises an asyncio.TimeoutError if it doesn't complete within the specified timeout.
import asyncio
async def long_running_task():
"""A task that takes 5 seconds to complete."""
print("Task started, will take 5 seconds...")
await asyncio.sleep(5)
print("Task finished!")
return "completed"
async def main():
print("Attempting to run task with a 3-second timeout...")
try:
# This will fail because the timeout (3s) is less than the task's duration (5s)
result = await asyncio.wait_for(long_running_task(), timeout=3.0)
print(f"Task successfully returned: {result}")
except asyncio.TimeoutError:
print("The task was cancelled due to a timeout!")
if __name__ == "__main__":
asyncio.run(main())
Output:
Attempting to run task with a 3-second timeout...
Task started, will take 5 seconds...
The task was cancelled due to a timeout!
When you stop your application (e.g., with Ctrl+C), you often want to clean up resources. This recipe shows how to catch the cancellation signal and perform cleanup.
Concept: Ctrl+C raises a KeyboardInterrupt, which asyncio.run() translates into a CancelledError inside the main task. We can catch this error to perform cleanup.
import asyncio
async def worker(name):
print(f"Worker {name} started.")
try:
while True:
await asyncio.sleep(1)
print(f"Worker {name} is running...")
except asyncio.CancelledError:
print(f"Worker {name} was cancelled. Cleaning up...")
# Simulate cleanup
await asyncio.sleep(0.5)
print(f"Worker {name} finished cleanup.")
raise # It's good practice to re-raise CancelledError
async def main():
# Create and run a task
task = asyncio.create_task(worker("A"))
# Let it run for a bit
await asyncio.sleep(3.5)
# Now, cancel the task
print("Main: cancelling the worker task.")
task.cancel()
try:
# Wait for the task to finish its cancellation routine
await task
except asyncio.CancelledError:
print("Main: worker task is now fully cancelled.")
if __name__ == "__main__":
# If you run this and press Ctrl+C, you will see a similar cleanup process
try:
asyncio.run(main())
except KeyboardInterrupt:
print("Program interrupted by user. Shutting down.")
Output:
Worker A started.
Worker A is running...
Worker A is running...
Worker A is running...
Main: cancelling the worker task.
Worker A was cancelled. Cleaning up...
Worker A finished cleanup.
Main: worker task is now fully cancelled.
asyncio.waitSometimes you don't need all results, just the fastest one (e.g., querying multiple redundant servers).
Concept: asyncio.wait() provides more control than gather. With return_when=asyncio.FIRST_COMPLETED, it returns as soon as any task finishes.
import asyncio
import random
async def fetch_data(server_id, delay):
"""Simulate fetching data from a server."""
print(f"Querying server {server_id}...")
await asyncio.sleep(delay)
return {"server": server_id, "data": f"Data from {server_id}"}
async def main():
tasks = [
asyncio.create_task(fetch_data(1, 2.0)),
asyncio.create_task(fetch_data(2, 1.0)), # This one is the fastest
asyncio.create_task(fetch_data(3, 3.0))
]
print("Waiting for the first task to complete...")
done, pending = await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED)
# Get the result from the completed task
first_result = done.pop().result()
print(f"First result received: {first_result}")
# The other tasks are still running in the background. We must cancel them.
print("Cancelling the pending tasks...")
for task in pending:
task.cancel()
# Await them to allow them to process the cancellation
await asyncio.gather(*pending, return_exceptions=True)
print("All pending tasks cancelled.")
if __name__ == "__main__":
asyncio.run(main())
Output:
Waiting for the first task to complete...
Querying server 1...
Querying server 2...
Querying server 3...
First result received: {'server': 2, 'data': 'Data from 2'}
Cancelling the pending tasks...
All pending tasks cancelled.
requests, file I/O)You cannot await a regular function. To use a blocking library like requests or standard file I/O in an asyncio app, you must run it in a separate thread to avoid blocking the event loop.
Concept: asyncio.to_thread() (Python 3.9+) is the modern, high-level way to run a blocking function in a separate thread and await its result. For older versions, use loop.run_in_executor().
import asyncio
import time
import requests # A popular, blocking HTTP library
def blocking_http_get(url):
"""A regular, blocking function that performs a network request."""
print(f"Starting blocking request to {url}...")
response = requests.get(url)
print(f"Finished blocking request to {url}.")
return response.status_code
async def main():
print("Starting async main function.")
# Run the blocking function in a separate thread
# The event loop will continue to run while this is executing.
status_code = await asyncio.to_thread(blocking_http_get, 'https://httpbin.org/delay/2')
print(f"Async main function got status: {status_code}")
print("Async main can do other things while waiting...")
# For Python < 3.9:
# async def main_legacy():
# loop = asyncio.get_running_loop()
# status_code = await loop.run_in_executor(
# None, # Use the default thread pool executor
# blocking_http_get,
# 'https://httpbin.org/delay/2'
# )
# print(f"Async main function got status: {status_code}")
if __name__ == "__main__":
asyncio.run(main())
Output:
Starting async main function.
Starting blocking request to https://httpbin.org/delay/2...
Async main can do other things while waiting...
Finished blocking request to https://httpbin.org/delay/2.
Async main function got status: 200
For heavy calculations that consume CPU (not just waiting for I/O), a thread won't help due to Python's Global Interpreter Lock (GIL). You need a separate process.
Concept: loop.run_in_executor() can be used with a ProcessPoolExecutor to run CPU-bound work in a separate process, allowing your asyncio app to remain responsive.
import asyncio
import time
from concurrent.futures import ProcessPoolExecutor
def cpu_bound_operation(x):
"""A function that simulates a heavy CPU-bound calculation."""
print(f"Starting CPU-bound operation for {x}...")
# This is a dummy calculation that will keep a CPU core busy.
count = 0
for i in range(10**7):
count += i
print(f"Finished CPU-bound operation for {x}.")
return x * x
async def main():
loop = asyncio.get_running_loop()
# Create a process pool executor.
# It's recommended to do this outside the main function or manage it carefully
# to avoid creating new pools on every call.
with ProcessPoolExecutor() as process_pool:
print("Submitting CPU-bound tasks to process pool...")
# Run the CPU-bound function in a separate process
future1 = loop.run_in_executor(process_pool, cpu_bound_operation, 2)
future2 = loop.run_in_executor(process_pool, cpu_bound_operation, 3)
# While CPU tasks run, the event loop is not blocked.
print("Event loop is free to do other work.")
await asyncio.sleep(1)
print("Slept for 1 second in main.")
# Await the results from the process pool
result1 = await future1
result2 = await future2
print(f"Result 1: {result1}")
print(f"Result 2: {result2}")
if __name__ == "__main__":
asyncio.run(main())
asyncio.SemaphoreIf you need to make many requests to an API with a rate limit, you can use a semaphore to ensure you never have more than N concurrent requests.
Concept: An asyncio.Semaphore is a counter that you acquire() before running a task and release() after. If the counter is zero, acquire() will wait until another task calls release().
import asyncio
import aiohttp # Async-native HTTP library
async def fetch_url(session, url, sem):
"""Fetch a URL, but acquire the semaphore first."""
# This 'async with' statement will wait until a slot in the semaphore is free.
async with sem:
print(f"Fetching {url}...")
async with session.get(url) as response:
data = await response.json()
print(f"Finished fetching {url}.")
return data['url']
async def main():
# Limit concurrency to 3 simultaneous requests
semaphore = asyncio.Semaphore(3)
urls_to_fetch = [f'https://httpbin.org/delay/{d}' for d in [2, 1, 3, 1, 2]]
async with aiohttp.ClientSession() as session:
tasks = [fetch_url(session, url, semaphore) for url in urls_to_fetch]
results = await asyncio.gather(*tasks)
print("All results:", results)
if __name__ == "__main__":
asyncio.run(main())
Observation: You will see up to 3 "Fetching..." messages appear at once, but never 4, even though there are 5 URLs.
asyncio.QueueA classic pattern where one or more "producer" coroutines add items to a queue, and one or more "consumer" coroutines process them.
Concept: asyncio.Queue is a thread-safe (and task-safe) async queue. await queue.put() adds an item, and await queue.get() removes an item, waiting if the queue is empty.
import asyncio
import random
async def producer(queue, name):
"""Produces random numbers and puts them into the queue."""
for i in range(5):
item = random.randint(1, 100)
await asyncio.sleep(random.random())
await queue.put(item)
print(f"Producer {name} produced -> {item} (qsize: {queue.qsize()})")
async def consumer(queue, name):
"""Consumes numbers from the queue."""
while True:
# Wait for an item from the producer
item = await queue.get()
print(f"Consumer {name} consumed <- {item} (qsize: {queue.qsize()})")
# Simulate work
await asyncio.sleep(random.uniform(0.5, 1.5))
# Notify the queue that the item has been processed
queue.task_done()
async def main():
queue = asyncio.Queue()
# Create producer and consumer tasks
producers = [asyncio.create_task(producer(queue, "P1")),
asyncio.create_task(producer(queue, "P2"))]
consumers = [asyncio.create_task(consumer(queue, "C1")),
asyncio.create_task(consumer(queue, "C2"))]
# Wait for all producers to finish
await asyncio.gather(*producers)
print("---- All producers have finished ----")
# Wait for the queue to be empty (all items processed by consumers)
await queue.join()
# All items are processed, so we can cancel the consumer tasks
for c in consumers:
c.cancel()
await asyncio.gather(*consumers, return_exceptions=True)
if __name__ == "__main__":
asyncio.run(main())
asyncio.EventAn Event is a simple way for one coroutine to signal to others that something has happened.
Concept: An asyncio.Event object has an internal flag. await event.wait() blocks until the flag is set to true. event.set() sets the flag to true, unblocking all waiting coroutines. event.clear() resets it.
import asyncio
async def waiter(event):
print("Waiting for the event to be set...")
await event.wait() # This will block until event.set() is called
print("Event was set! I can now proceed.")
async def setter(event):
print("I'm going to sleep for 3 seconds, then set the event.")
await asyncio.sleep(3)
event.set() # This unblocks the waiter
print("Event has been set.")
async def main():
# Create an event object
event = asyncio.Event()
# Create tasks that share the same event object
waiter_task = asyncio.create_task(waiter(event))
setter_task = asyncio.create_task(setter(event))
await asyncio.gather(waiter_task, setter_task)
if __name__ == "__main__":
asyncio.run(main())
Output:
Waiting for the event to be set...
I'm going to sleep for 3 seconds, then set the event.
Event has been set.
Event was set! I can now proceed.
asyncio.create_subprocess_shellRun a shell command as a separate process and asynchronously read its output.
Concept: asyncio.create_subprocess_shell starts a subprocess. You can then await on its stdout, stderr, and wait() for it to complete.
import asyncio
import sys
async def run_command(cmd):
"""Run a shell command and stream its output."""
print(f"--- Running command: {cmd} ---")
# The command to run (use 'ping' on Windows, 'ping -c 4' on Linux/macOS)
process = await asyncio.create_subprocess_shell(
cmd,
stdout=asyncio.subprocess.PIPE,
stderr=asyncio.subprocess.PIPE
)
# Asynchronously read stdout line by line
while True:
line = await process.stdout.readline()
if not line:
break
print(f"STDOUT: {line.decode().strip()}")
# Wait for the process to terminate and get the return code
return_code = await process.wait()
print(f"--- Command finished with return code: {return_code} ---")
return return_code
async def main():
if sys.platform == "win32":
command = "ping 1.1.1.1"
else:
command = "ping -c 4 1.1.1.1"
await run_command(command)
if __name__ == "__main__":
asyncio.run(main())
This shows the fundamental networking capabilities of asyncio.
Concept: asyncio.start_server creates a TCP server. The callback you provide is an async function that receives a StreamReader and StreamWriter for each new client connection.
Server Code (server.py)
import asyncio
async def handle_echo(reader, writer):
"""Callback for each client connection."""
addr = writer.get_extra_info('peername')
print(f"Received connection from {addr}")
while True:
data = await reader.read(100) # Read up to 100 bytes
if not data: # EOF, client closed connection
break
message = data.decode()
print(f"Received '{message}' from {addr}")
print(f"Sending back: '{message}'")
writer.write(data)
await writer.drain() # Wait until the buffer is flushed
print(f"Closing connection with {addr}")
writer.close()
await writer.wait_closed()
async def main():
server = await asyncio.start_server(handle_echo, '127.0.0.1', 8888)
addrs = ', '.join(str(sock.getsockname()) for sock in server.sockets)
print(f'Serving on {addrs}')
async with server:
await server.serve_forever()
if __name__ == "__main__":
print("Starting echo server. Press Ctrl+C to stop.")
try:
asyncio.run(main())
except KeyboardInterrupt:
print("Server shutting down.")
Client Code (client.py)
import asyncio
async def tcp_echo_client(message):
reader, writer = await asyncio.open_connection('127.0.0.1', 8888)
print(f'Sending: {message!r}')
writer.write(message.encode())
await writer.drain()
data = await reader.read(100)
print(f'Received: {data.decode()!r}')
print('Closing the connection')
writer.close()
await writer.wait_closed()
async def main():
await tcp_echo_client('Hello World!')
await tcp_echo_client('This is asyncio!')
if __name__ == "__main__":
asyncio.run(main())
How to run:
python server.py in one terminal.python client.py in another terminal. You will see the communication logged in both terminals.