import hashlib import json import os import subprocess def write(path, value): tmp = path.with_suffix(path.suffix + '.tmp') with tmp.open('w') as f: json.dump(value, f, indent=2, sort_keys=True); f.write('\n'); f.flush(); os.fsync(f.fileno()) tmp.replace(path) def run(argv, target, timeout=180, check=True): p = subprocess.run(argv, capture_output=True, timeout=timeout) target.with_suffix('.stdout.log').write_bytes(p.stdout) target.with_suffix('.stderr.log').write_bytes(p.stderr) record = {'argv': argv, 'returncode': p.returncode, 'stdout_sha256': hashlib.sha256(p.stdout).hexdigest(), 'stderr_sha256': hashlib.sha256(p.stderr).hexdigest()} write(target.with_suffix('.execution.json'), record) if check and p.returncode: raise RuntimeError(f'{target.name}: exit {p.returncode}') return record