(
script: str,
success_message: str,
failure_message: str,
*,
env_overrides: dict[str, str] | None = None,
cleanup_paths: list[Path] | None = None,
)
| 491 | |
| 492 | |
| 493 | def _stream_python_script( |
| 494 | script: str, |
| 495 | success_message: str, |
| 496 | failure_message: str, |
| 497 | *, |
| 498 | env_overrides: dict[str, str] | None = None, |
| 499 | cleanup_paths: list[Path] | None = None, |
| 500 | ): |
| 501 | cleanup_paths = cleanup_paths or [] |
| 502 | temp_path: Path | None = None |
| 503 | try: |
| 504 | with tempfile.NamedTemporaryFile(delete=False, suffix=".py", dir=PROJECT_DIR, encoding="utf-8", mode="w") as temp_script: |
| 505 | temp_script.write(script) |
| 506 | temp_path = Path(temp_script.name) |
| 507 | |
| 508 | command = [sys.executable, str(temp_path)] |
| 509 | yield f"$ {_format_command(command)}\n" |
| 510 | |
| 511 | env = os.environ.copy() |
| 512 | env["PYTHONUNBUFFERED"] = "1" |
| 513 | env["PYTHONIOENCODING"] = "utf-8" |
| 514 | if env_overrides: |
| 515 | env.update(env_overrides) |
| 516 | |
| 517 | try: |
| 518 | process = subprocess.Popen( |
| 519 | command, |
| 520 | cwd=PROJECT_DIR, |
| 521 | env=env, |
| 522 | stdout=subprocess.PIPE, |
| 523 | stderr=subprocess.STDOUT, |
| 524 | text=True, |
| 525 | encoding="utf-8", |
| 526 | errors="replace", |
| 527 | bufsize=1, |
| 528 | ) |
| 529 | except OSError as exc: |
| 530 | yield f"Failed to start process: {exc}\n" |
| 531 | yield _stream_status(False, failure_message) |
| 532 | return |
| 533 | |
| 534 | if process.stdout is not None: |
| 535 | for line in process.stdout: |
| 536 | yield line |
| 537 | |
| 538 | returncode = process.wait() |
| 539 | if returncode != 0: |
| 540 | yield f"\nProcess exited with code {returncode}.\n" |
| 541 | yield _stream_status(False, failure_message) |
| 542 | return |
| 543 | |
| 544 | yield _stream_status(True, success_message) |
| 545 | finally: |
| 546 | if temp_path and temp_path.exists(): |
| 547 | try: |
| 548 | temp_path.unlink() |
| 549 | except OSError: |
| 550 | pass |
no test coverage detected