把 code 写到临时文件并跑,返回 (成功?, stderr)。
(code: str, timeout: int = 10)
| 32 | |
| 33 | |
| 34 | def run_block(code: str, timeout: int = 10) -> tuple[bool, str]: |
| 35 | """把 code 写到临时文件并跑,返回 (成功?, stderr)。""" |
| 36 | with tempfile.NamedTemporaryFile( |
| 37 | mode="w", suffix=".py", delete=False, encoding="utf-8" |
| 38 | ) as f: |
| 39 | f.write(code) |
| 40 | path = f.name |
| 41 | try: |
| 42 | result = subprocess.run( |
| 43 | [sys.executable, path], |
| 44 | capture_output=True, |
| 45 | text=True, |
| 46 | timeout=timeout, |
| 47 | ) |
| 48 | return result.returncode == 0, result.stderr |
| 49 | except subprocess.TimeoutExpired: |
| 50 | return False, f"timeout after {timeout}s" |
| 51 | finally: |
| 52 | Path(path).unlink(missing_ok=True) |
| 53 | |
| 54 | |
| 55 | def main() -> int: |