MCPcopy
hub / github.com/walter201230/Python / run_block

Function run_block

tools/example_runner.py:34–52  ·  view source on GitHub ↗

把 code 写到临时文件并跑,返回 (成功?, stderr)。

(code: str, timeout: int = 10)

Source from the content-addressed store, hash-verified

32
33
34def 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
55def main() -> int:

Callers 1

mainFunction · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected