Python asyncio Advanced

Advanced loop management, low-level scheduling, and platform-aware asyncio usage.

View
StandardDetailedCompact
Export
Copy the compact sheet, download it, or print it.
Download
`D` dense toggle · `C` copy all
## Event Loop Management
Schedule a callback later
import asyncio

def on_timer():
    print("timer fired")

async def main():
    loop = asyncio.get_running_loop()
    loop.call_later(0.2, on_timer)
    await asyncio.sleep(0.3)

asyncio.run(main())

# Run a plain callback after a delay.

Schedule from another thread
import asyncio
import threading

async def main():
    loop = asyncio.get_running_loop()
    event = asyncio.Event()

    def notify():
        loop.call_soon_threadsafe(event.set)

    threading.Thread(target=notify).start()
    await event.wait()
    print("notified")

asyncio.run(main())

# Use `call_soon_threadsafe()` when another thread must notify the loop.

Submit a coroutine from another thread
import asyncio
import threading

async def echo():
    return "ok"

async def main():
    loop = asyncio.get_running_loop()
    result_holder = {}

    def worker():
        future = asyncio.run_coroutine_threadsafe(echo(), loop)
        result_holder["value"] = future.result()

    t = threading.Thread(target=worker)
    t.start()
    await asyncio.sleep(0.1)
    t.join()
    print(result_holder["value"])

asyncio.run(main())

# Use `run_coroutine_threadsafe()` with a loop reference.

## Migration and Platform Notes
Prefer `get_running_loop()` in async code
import asyncio

async def main():
    loop = asyncio.get_running_loop()
    print(loop)

asyncio.run(main())

# Modern replacement for older loop access patterns.

Know the file I/O caveat
# asyncio can monitor sockets and many OS handles, but regular file I/O
# is not made non-blocking just by using asyncio. Use threads or subprocesses
# for blocking file operations when needed.

# Document the limitation around file descriptor watching for ordinary file I/O.

Recommended next

No recommendations yet.