Python asyncio Streams and Subprocesses/Run blocking I/O in a thread

Use `asyncio.to_thread()` for simple thread offloading.

Section: Threads and Blocking Code

Run blocking I/O in a thread

python
python
import asyncio
import time

def blocking_read():
    time.sleep(1)
    return "finished"

async def main():
    result = await asyncio.to_thread(blocking_read)
    print(result)

asyncio.run(main())
Explanation

`asyncio.to_thread()` is a high-level helper for running I/O-bound blocking functions in a separate thread.

Learn the surrounding workflow

Compare similar commands or jump into common fixes when this command is part of a bigger troubleshooting path.

Related commands

Same sheet · prioritizing Threads and Blocking Code
Use `run_in_executor()`
Offload work with explicit loop executor integration.
OpenIn sheetpythonsame section
Open a TCP connection
Use stream reader and writer objects.
Run a subprocess with exec
Capture stdout and stderr asynchronously.
Start a TCP server
Serve client connections with async handlers.
Run a shell command asynchronously
Spawn a shell pipeline with `create_subprocess_shell()`.