objectif
Lire la sortie d’un processus ligne par ligne en temps quasi-réel.
code minimal
import subprocess, sys
p = subprocess.Popen([sys.executable, "-c", "print('a'); print('b')"], stdout=subprocess.PIPE, text=True)
lines = [l.strip() for l in p.stdout]
p.wait()
print(lines == ["a","b"]) # attendu: True
utilisation
import subprocess, sys
p = subprocess.Popen([sys.executable, "-c", "print('x')"], stdout=subprocess.PIPE, text=True)
out = p.stdout.read().strip()
p.wait()
print(out == "x")
variante(s) utile(s)
import subprocess, sys
p = subprocess.Popen([sys.executable, "-c", "import time;print('1');time.sleep(0.01);print('2')"], stdout=subprocess.PIPE, text=True)
out = p.communicate()[0].splitlines()
print(out[-1] == "2")
notes
- Utilisez text=True pour obtenir des str et non des bytes.
- communicate() évite les deadlocks quand il y a stdout+stderr.