Execute code and return std outputs and std error. Args: code (str): Code to execute. time_out (int): time out, in second. Returns: str: std output and std error
(code: str, time_out: int = 60)
| 1 | def execute_code(code: str, time_out: int = 60) -> str: |
| 2 | """ |
| 3 | Execute code and return std outputs and std error. |
| 4 | |
| 5 | Args: |
| 6 | code (str): Code to execute. |
| 7 | time_out (int): time out, in second. |
| 8 | |
| 9 | Returns: |
| 10 | str: std output and std error |
| 11 | """ |
| 12 | import os |
| 13 | import sys |
| 14 | import subprocess |
| 15 | import uuid |
| 16 | from pathlib import Path |
| 17 | |
| 18 | def __write_script_file(_code: str): |
| 19 | _workspace = Path(os.getenv('TEMP_CODE_DIR', 'temp')).resolve() |
| 20 | _workspace.mkdir(exist_ok=True) |
| 21 | filename = f"{uuid.uuid4()}.py" |
| 22 | code_path = _workspace / filename |
| 23 | code_content = _code if _code.endswith("\n") else _code + "\n" |
| 24 | code_path.write_text(code_content, encoding="utf-8") |
| 25 | return code_path |
| 26 | |
| 27 | def __default_interpreter() -> str: |
| 28 | return sys.executable or "python3" |
| 29 | |
| 30 | script_path = None |
| 31 | stdout = "" |
| 32 | stderr = "" |
| 33 | |
| 34 | try: |
| 35 | script_path = __write_script_file(code) |
| 36 | workspace = script_path.parent |
| 37 | |
| 38 | cmd = [__default_interpreter(), str(script_path.resolve())] |
| 39 | |
| 40 | try: |
| 41 | completed = subprocess.run( |
| 42 | cmd, |
| 43 | cwd=str(workspace), |
| 44 | capture_output=True, |
| 45 | timeout=time_out, |
| 46 | check=False |
| 47 | ) |
| 48 | stdout = completed.stdout.decode('utf-8', errors="replace") |
| 49 | stderr = completed.stderr.decode('utf-8', errors="replace") |
| 50 | except subprocess.TimeoutExpired as e: |
| 51 | stdout = e.stdout.decode('utf-8', errors="replace") if e.stdout else "" |
| 52 | stderr = e.stderr.decode('utf-8', errors="replace") if e.stderr else "" |
| 53 | stderr += f"\nError: Execution timed out after {time_out} seconds." |
| 54 | except Exception as e: |
| 55 | stderr = f"Execution error: {str(e)}" |
| 56 | |
| 57 | except Exception as e: |
| 58 | stderr = f"Setup error: {str(e)}" |
| 59 | finally: |
| 60 | if script_path and script_path.exists(): |
nothing calls this directly
no test coverage detected