CLI journal project (4/6): asyncio and batch reads
Use gather, a semaphore, and run_in_executor so disk reads of several logs do not block the event loop. Twelve exercises, plus a sync fallback.
Getting started
Home Assistant
Buying
Use gather, a semaphore, and run_in_executor so disk reads of several logs do not block the event loop. Twelve exercises, plus a sync fallback.


AI-generated illustration
Some links on this page are affiliate links. The button opens Amazon so you can check today’s price.
When you analyze several large files, you can run the work in parallel: asyncio.gather starts tasks that wait on I/O. Careful: reading a file with synchronous open() blocks the loop. A common pattern is await loop.run_in_executor(None, parse_file_sync, path), where parse_file_sync reads and aggregates in a thread (disk I/O often releases the GIL).
A minimal alternative is to stay fully synchronous with concurrent.futures.ThreadPoolExecutor for this project — but document the choice: the advanced course asks you to illustrate asyncio.
Previous chapter: decorators and metrics.
async def process_paths(paths: list[Path]) -> Report:
loop = asyncio.get_running_loop()
sem = asyncio.Semaphore(4)
async def one(p: Path):
async with sem:
return await loop.run_in_executor(None, parse_and_count, p)
parts = await asyncio.gather(*[one(p) for p in paths])
return merge_reports(parts)
Exercise 1 — Write asyncio.run plus a main() coroutine that await asyncio.sleep(0). Easy
import asyncio
async def main():
await asyncio.sleep(0)
asyncio.run(main())
Exercise 2 — Limit concurrency to 4 files with Semaphore(4). Intermediate
sem = asyncio.Semaphore(4)
async with sem:
...
Exercise 3 — Why run_in_executor for open / reading? Intermediate
# Avoid blocking the event loop on synchronous I/O.
Exercise 4 — Merge two Counter objects with sum or counter.update. Easy
from collections import Counter
a = Counter({"INFO": 1})
a.update(Counter({"INFO": 2, "ERROR": 1}))
Exercise 5 — gather with return_exceptions=True: the case of a missing file. Hard
# Collect FileNotFoundError in the list for an error report.
Exercise 6 — asyncio.run must not be called inside a coroutine — why? Intermediate
# Nested loops are not allowed; await coroutines instead.
Exercise 7 — Benchmark: sync versus async plus executor on 10 files — when is the gain zero? Hard
On a slow disk or with tiny files; scheduling overhead.
Exercise 8 — aiofiles (third party) — when should you add it? Intermediate
Native async read and write without a thread pool; a pip dependency.
Exercise 9 — uvloop — the context (Linux/macOS). Hard
A faster alternative event loop; optional.
Exercise 10 — asyncio.to_thread (3.9+) — equivalent to run_in_executor. Intermediate
await asyncio.to_thread(parse_and_count, path)
Exercise 11 — A synchronous main calls asyncio.run once — a single entry point. Easy
def main():
return asyncio.run(amain())
Exercise 12 — Document the fallback: if --no-async, process files sequentially and synchronously. Hard
Works in restricted environments; simpler to debug.
Check today’s price on Amazon
Was this page helpful?
Thank you!
What should we improve?
Torn between two models or stuck on a build? Drop us a line and we will get back to you by email.
Cookies and analytics
We use Google Analytics 4 to understand how the site is used (page views, navigation). It is only switched on if you accept. Declining does not stop you using the site. More: cookie settings and privacy policy (in French).