Python Asyncio

Concurrent I/O with async/await, tasks, and timeouts.

  • python asyncio
  • async await
  • asyncio.gather
  • httpx async
  • coroutine

Python Asyncio

Concurrent I/O with async/await, tasks, and timeouts.

Commands

CommandWhat it does
async def fetch(url): ...Coroutine definition
await asyncio.gather(a(), b())Run concurrently
asyncio.run(main())Entry point (runs the loop)
async with httpx clientAsync HTTP session
asyncio wait_for timeout 5Bounded wait

Example

import asyncio
async def main():
    await asyncio.gather(ping("a"), ping("b"))
asyncio.run(main())

FAQ

asyncio vs threads?

Asyncio wins for many I/O-bound waits in one thread; threads (or processes) suit CPU work and blocking libs.

Can I call blocking code in async?

Offload with asyncio.to_thread, or it stalls the whole event loop.

常見問題

asyncio vs threads?
Asyncio wins for many I/O-bound waits in one thread; threads (or processes) suit CPU work and blocking libs.
Can I call blocking code in async?
Offload with asyncio.to_thread, or it stalls the whole event loop.

Python