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.
Python's asyncio library provides a powerful framework for writing asynchronous code, allowing you to handle concurrent tasks efficiently. Below are some common recipes and patterns for using asyncio effectively.
Use asyncio.gather to run multiple coroutines concurrently.
import asyncio
async def task(id, delay):
await asyncio.sleep(delay)
return f"Task {id} completed"
async def main():
tasks = [task(i, i) for i in range(1, 4)]
results = await asyncio.gather(*tasks)
print(results)
asyncio.run(main())
Use asyncio.wait_for to enforce a timeout on a coroutine.
import asyncio
async def slow_task():
await asyncio.sleep(5)
return "Task completed"
async def main():
try:
result = await asyncio.wait_for(slow_task(), timeout=2)
print(result)
except asyncio.TimeoutError:
print("Task timed out!")
asyncio.run(main())
Use a semaphore to limit the number of concurrent tasks.
import asyncio
async def task(id, semaphore):
async with semaphore:
await asyncio.sleep(1)
return f"Task {id} completed"
async def main():
semaphore = asyncio.Semaphore(2) # Allow 2 concurrent tasks
tasks = [task(i, semaphore) for i in range(1, 5)]
results = await asyncio.gather(*tasks)
print(results)
asyncio.run(main())
Use async for to iterate over asynchronous iterators.
import asyncio
async def async_range(n):
for i in range(n):
await asyncio.sleep(0.1)
yield i
async def main():
async for i in async_range(5):
print(i)
asyncio.run(main())
Use loop.run_in_executor to run blocking code in a thread pool.
import asyncio
import time
def blocking_task(id):
time.sleep(1)
return f"Blocking Task {id} completed"
async def main():
loop = asyncio.get_running_loop()
tasks = [loop.run_in_executor(None, blocking_task, i) for i in range(1, 4)]
results = await asyncio.gather(*tasks)
print(results)
asyncio.run(main())
Define an asynchronous context manager using async with.
import asyncio
class AsyncContextManager:
async def __aenter__(self):
print("Entering context")
await asyncio.sleep(1)
return self
async def __aexit__(self, exc_type, exc, tb):
print("Exiting context")
await asyncio.sleep(1)
async def main():
async with AsyncContextManager() as cm:
print("Inside context")
asyncio.run(main())
Use asyncio.Queue for producer-consumer patterns.
import asyncio
async def producer(queue):
for i in range(5):
await queue.put(f"Item {i}")
await asyncio.sleep(1)
async def consumer(queue):
while True:
item = await queue.get()
if item is None:
break
print(f"Consumed: {item}")
queue.task_done()
async def main():
queue = asyncio.Queue()
asyncio.create_task(producer(queue))
asyncio.create_task(consumer(queue))
await queue.join()
asyncio.run(main())
Cancel tasks gracefully using Task.cancel().
import asyncio
async def cancellable_task():
try:
while True:
await asyncio.sleep(1)
print("Task running...")
except asyncio.CancelledError:
print("Task cancelled!")
raise
async def main():
task = asyncio.create_task(cancellable_task())
await asyncio.sleep(3)
task.cancel()
try:
await task
except asyncio.CancelledError:
pass
asyncio.run(main())
Create an asynchronous TCP server and client.
import asyncio
async def handle_client(reader, writer):
data = await reader.read(100)
message = data.decode()
print(f"Received: {message}")
writer.write(f"Echo: {message}".encode())
await writer.drain()
writer.close()
async def main():
server = await asyncio.start_server(handle_client, '127.0.0.1', 8888)
async with server:
await server.serve_forever()
asyncio.run(main())
Client:
import asyncio
async def tcp_client():
reader, writer = await asyncio.open_connection('127.0.0.1', 8888)
writer.write(b"Hello World")
await writer.drain()
data = await reader.read(100)
print(f"Received: {data.decode()}")
writer.close()
asyncio.run(tcp_client())
Run and interact with subprocesses asynchronously.
import asyncio
async def run_subprocess():
process = await asyncio.create_subprocess_exec(
"ls", "-l", stdout=asyncio.subprocess.PIPE
)
stdout, stderr = await process.communicate()
print(f"Output: {stdout.decode()}")
asyncio.run(run_subprocess())
These recipes cover common use cases for asyncio. Depending on your needs, you can combine these patterns to build more complex asynchronous applications.