Files
mtusi2026lab2/scripts/run_and_save.py
T
2026-10-23 14:09:32 +03:00

65 lines
2.5 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
"""Выполнить команду и сохранить её вывод в файл вместе с датой, коммитом и кодом возврата.
python scripts/run_and_save.py evidence/01.txt -- python scripts/check_contract.py
"""
import os
import subprocess
import sys
import time
from datetime import datetime, timezone
from pathlib import Path
def git_commit(root: Path) -> str:
"""Короткий hash текущего коммита или пояснение, почему его нет."""
try:
out = subprocess.run(["git", "rev-parse", "--short", "HEAD"], cwd=str(root), capture_output=True,
text=True, timeout=5)
return out.stdout.strip() if out.returncode == 0 and out.stdout.strip() else "нет (git не используется)"
except Exception:
return "нет (git не найден)"
def main() -> int:
"""Выполнить команду после --, записать отчёт и вернуть её код возврата."""
argv = sys.argv[1:]
if len(argv) < 3 or argv[1] != "--":
print(__doc__)
return 2
target = Path(argv[0])
command = argv[2:]
root = Path(__file__).resolve().parents[1]
env = dict(os.environ, PYTHONIOENCODING="utf-8", PYTHONUTF8="1")
started = time.monotonic()
try:
done = subprocess.run(command, capture_output=True, env=env, cwd=str(root))
output = (done.stdout + done.stderr).decode("utf-8", errors="replace")
code = done.returncode
except FileNotFoundError:
output = "Команда не найдена: %s\n" % command[0]
code = 127
elapsed = time.monotonic() - started
text = "\n".join([
"# Дата (UTC): " + datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S"),
"# Commit: " + git_commit(root),
"# Команда: " + " ".join(command),
"# ---------------------------------------- вывод ----------------------------------------",
output.rstrip(),
"# ---------------------------------------------------------------------------------------",
"# Код возврата: %d" % code,
"# Время выполнения: %.2f с" % elapsed,
"",
])
target.parent.mkdir(parents=True, exist_ok=True)
target.write_text(text, encoding="utf-8")
sys.stdout.buffer.write(text.encode("utf-8", errors="replace"))
print("\n[сохранено в %s]" % target)
return code
if __name__ == "__main__":
sys.exit(main())