Spaces:
Paused
Paused
| 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} |