13. Bibliothèque Standard

Modules essentiels : os, sys, datetime, re, math, random, statistics, collections, functools, argparse.


13.1 sys

import sys
 
sys.argv            # arguments de la ligne de commande
sys.path            # chemins d'import
sys.platform        # "darwin", "linux", "win32"
sys.exit(code)      # quitter
sys.version         # "3.13.2 (...)"

13.2 os

import os
 
os.getcwd()             # répertoire courant
os.chdir("/tmp")        # changer de répertoire
os.listdir(".")         # lister le dossier
os.mkdir("dossier")     # créer dossier
os.remove("fichier")    # supprimer fichier
os.environ["HOME"]      # variables d'environnement
os.path.join("a", "b")  # "a/b" (portable)
os.path.exists("f")     # True/False

Préférer pathlib (leçon 12) pour les chemins — plus moderne.

13.3 datetime

from datetime import datetime, date, time, timedelta
 
# Maintenant
dt = datetime.now()                  # 2026-06-02 14:30:00...
 
# Construction
d = date(2026, 6, 2)
t = time(14, 30)
dt = datetime(2026, 6, 2, 14, 30)
 
# Formatage
dt.strftime("%Y-%m-%d %H:%M")        # "2026-06-02 14:30"
datetime.strptime("2026-06-02", "%Y-%m-%d")
 
# Opérations
dt + timedelta(days=7)
dt - timedelta(hours=3)

13.4 re — expressions régulières

import re
 
re.search(r"\d+", "abc123")          # match sur "123"
re.match(r"\d+", "123abc")           # match au début
re.fullmatch(r"\d+", "123")          # match total
re.findall(r"\d+", "a1 b22 c333")    # ["1", "22", "333"]
re.sub(r"\d+", "X", "a1b2")         # "aXbX"
re.split(r"\s+", "a  b   c")        # ["a", "b", "c"]

Groupes :

m = re.search(r"(\w+)@(\w+\.\w+)", "user@example.com")
m.group(0)    # "user@example.com"
m.group(1)    # "user"
m.group(2)    # "example.com"

Compilation (pour performance) :

pattern = re.compile(r"\d+")
pattern.findall("a1b2c3")

13.5 math

import math
 
math.sqrt(16)       # 4.0
math.log(math.e)    # 1.0
math.log2(1024)     # 10.0
math.log10(1000)    # 3.0
math.exp(1)         # e
math.sin, math.cos, math.tan
math.pi, math.e, math.inf, math.nan
math.floor(3.7)     # 3
math.ceil(3.1)      # 4
math.comb(5, 2)     # 10 (coefficient binomial)

13.6 random

import random
 
random.random()              # [0.0, 1.0)
random.randint(1, 6)         # entier entre 1 et 6
random.uniform(0, 10)        # float entre 0 et 10
random.choice(["a", "b", "c"])  # élément aléatoire
random.sample(pop, k=3)      # 3 éléments sans remise
random.shuffle(liste)        # mélanger sur place
random.seed(42)              # reproductibilité

13.7 statistics

from statistics import mean, median, stdev, variance
 
mean([1, 2, 3, 4, 5])       # 3.0
median([1, 2, 3, 4, 100])   # 3.0
stdev([1, 2, 3, 4])          # écart-type

13.8 functools

from functools import partial, lru_cache, reduce
 
# Currying partiel
def puissance(base, exp):
    return base ** exp
 
carré = partial(puissance, exp=2)
carré(5)                     # 25
 
# Mémoïsation
@lru_cache(maxsize=128)
def fib(n):
    return n if n < 2 else fib(n-1) + fib(n-2)
 
# Reduce
reduce(lambda a, b: a * b, [1, 2, 3, 4])  # 24

13.9 argparse

import argparse
 
parser = argparse.ArgumentParser(description="Mon script")
parser.add_argument("input", help="Fichier d'entrée")
parser.add_argument("-o", "--output", default="sortie.txt")
parser.add_argument("-v", "--verbose", action="store_true")
args = parser.parse_args()
print(args.input, args.output)

13.10 copy

import copy
 
original = [[1, 2], [3, 4]]
copie = copy.copy(original)      # copie superficielle
profonde = copy.deepcopy(original)  # copie complète

13.11 hashlib

import hashlib
 
hashlib.md5(b"data").hexdigest()
hashlib.sha256(b"data").hexdigest()

13.12 logging

import logging
logging.basicConfig(level=logging.INFO,
                    format="%(levelname)s: %(message)s")
logging.info("Information")
logging.warning("Attention")
logging.error("Erreur")

🔗 ← Retour au cours · ← précédent · Suivant →