Spaces:
Paused
Paused
Download code_executor.py from JatinAutonomousLabs/SPOC_V1: direct link, hf CLI and curl.
- Browser
- Download file 1.22 kB
-
https://huggingface.co/spaces/JatinAutonomousLabs/SPOC_V1/resolve/main/code_executor.py
- Command line
-
hf download hf://spaces/JatinAutonomousLabs/SPOC_V1/code_executor.py
-
curl -L -o code_executor.py https://huggingface.co/spaces/JatinAutonomousLabs/SPOC_V1/resolve/main/code_executor.py
1.22 kB
| import subprocess | |
| import sys | |
| import os | |
| import tempfile | |
| import shutil | |
| def execute_python_code(code: str, timeout: int = 30) -> dict: | |
| """ | |
| Executes Python code in a temporary directory and returns the output. | |
| """ | |
| temp_dir = tempfile.mkdtemp() | |
| script_path = os.path.join(temp_dir, "script.py") | |
| with open(script_path, "w") as f: | |
| f.write(code) | |
| python_executable = sys.executable | |
| try: | |
| print(f"🧪 Executing code in a temporary environment...") | |
| process = subprocess.run( | |
| [python_executable, script_path], | |
| capture_output=True, | |
| text=True, | |
| timeout=timeout, | |
| cwd=temp_dir | |
| ) | |
| stdout = process.stdout | |
| stderr = process.stderr | |
| success = process.returncode == 0 | |
| except subprocess.TimeoutExpired: | |
| stdout = "" | |
| stderr = f"Execution timed out after {timeout} seconds." | |
| success = False | |
| except Exception as e: | |
| stdout = "" | |
| stderr = f"An unexpected error occurred: {str(e)}" | |
| success = False | |
| finally: | |
| shutil.rmtree(temp_dir) | |
| return {"stdout": stdout, "stderr": stderr, "success": success} |