示例工程 10-type-annotations-mypy
10-type-annotations-mypy/02-mypy-catches/capture_mypy.py
"""重新生成 mypy-before.txt / mypy-after.txt(需要已安装 mypy)。"""
from __future__ import annotations
import shutil
import subprocess
import sys
import tempfile
from pathlib import Path
HERE = Path(__file__).parent
def run_fixture(fixture: str) -> str:
"""把 .py.txt 复制成临时 .py,在临时目录里跑 mypy --strict。"""
filename = fixture.removesuffix(".txt")
with tempfile.TemporaryDirectory() as tmp:
target = Path(tmp) / filename
shutil.copyfile(HERE / fixture, target)
proc = subprocess.run(
[sys.executable, "-m", "mypy", "--strict", filename],
cwd=tmp,
capture_output=True,
text=True,
check=False,
)
return proc.stdout + proc.stderr
def main() -> None:
for fixture in ("before.py.txt", "after.py.txt"):
output = run_fixture(fixture)
output_path = HERE / f"mypy-{fixture.removesuffix('.py.txt')}.txt"
output_path.write_text(output, encoding="utf-8")
print(f"=== {output_path.name} ===")
print(output, end="")
if __name__ == "__main__":
main()