Enregistrer

Projet Journal CLI (4/6) : asyncio et batch

gather, semaphore, run_in_executor pour lecture disque ; pas de blocage ; 12 exercices.

Illustration : faisceaux lumineux parallèles transportant de petites tâches vers un ordinateur portable, image du traitement asynchrone par lots

Illustration générée par IA

Quand tu analyses plusieurs gros fichiers, tu peux paralléliser le travail : asyncio.gather pour lancer des tâches qui attendent des I/O. Attention : la lecture fichier avec open() synchrone bloque la boucle — pattern courant : await loop.run_in_executor(None, parse_file_sync, path) où parse_file_sync lit et agrège en thread (I/O disque libère le GIL souvent).

En alternative minimaliste, rester 100 % synchrone avec concurrent.futures.ThreadPoolExecutor pour ce projet — mais documente le choix : le cours avancé demande d’illustrer asyncio.

Schéma recommandé

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)

Exercices (12)

Exercice 1 — Écris asyncio.run + coroutine main() qui await asyncio.sleep(0). Simple

Afficher la solution
import asyncio
async def main():
    await asyncio.sleep(0)
asyncio.run(main())

Exercice 2 — Limite 4 fichiers simultanés avec Semaphore(4). Intermédiaire

Afficher la solution
sem = asyncio.Semaphore(4)
async with sem:
    ...

Exercice 3 — Pourquoi run_in_executor pour open / lecture ? Intermédiaire

Afficher la solution
# Évite de bloquer la boucle d'événements sur I/O synchrone.

Exercice 4 — Fusionne deux Counter avec sum ou counter.update. Simple

Afficher la solution
from collections import Counter
a = Counter({"INFO": 1})
a.update(Counter({"INFO": 2, "ERROR": 1}))

Exercice 5 — gather avec return_exceptions=True : cas d’un fichier manquant. Difficile

Afficher la solution
# Récupérer FileNotFoundError dans la liste pour rapport d'erreurs.

Exercice 6 — asyncio.run ne doit pas être appelé dans une coroutine — pourquoi ? Intermédiaire

Afficher la solution
# Boucles imbriquées interdites ; utiliser await sur coroutines.

Exercice 7 — Benchmark : version sync vs async+executor sur 10 fichiers — quand le gain est nul ? Difficile

Afficher la solution
Sur disque lent ou fichiers minuscules ; overhead de scheduling.

Exercice 8 — aiofiles (tiers) — quand l’ajouter ? Intermédiaire

Afficher la solution
Lecture/écriture async native sans thread pool ; dépendance pip.

Exercice 9 — uvloop — contexte (Linux/macOS). Difficile

Afficher la solution
Boucle alternative plus rapide ; optionnel.

Exercice 10 — asyncio.to_thread (3.9+) — équivalent à run_in_executor. Intermédiaire

Afficher la solution
await asyncio.to_thread(parse_and_count, path)

Exercice 11 — main synchrone appelle asyncio.run une fois — point d’entrée unique. Simple

Afficher la solution
def main():
    return asyncio.run(amain())

Exercice 12 — Documente le fallback : si --no-async, traitement séquentiel synchrone. Difficile

Afficher la solution
Compatibilité environnements restreints ; debug plus simple.

Suite

Typage et mypy

Amazon (partenaire)

Cette page vous a-t-elle été utile ?

Une question sur cet article ou besoin d'un conseil ? Posez-la ici

Vous hésitez entre deux modèles ou vous avez besoin d'aide sur un montage ? Écrivez-nous, nous vous répondons rapidement par e-mail.