import sys import subprocess import tempfile import pathlib def test_exit(): with tempfile.TemporaryDirectory() as tmp_fn: tmp = pathlib.Path(tmp_fn) ham = tmp / "ham.py" ham.write_text("raise KeyboardInterrupt") assert subprocess.run([sys.executable, ham]).returncode == -2 assert ( subprocess.run([sys.executable, "-m", ham.name], cwd=ham.parent).returncode == -2 ) if __name__ == "__main__": test_exit()