Spaces:
Sleeping
Sleeping
File size: 1,400 Bytes
8e3a425 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | # sandbox/secure_executor.py
"""
Exécution de code Python sécurisée (sandbox basique via subprocess).
Remplace l'ancienne dépendance inexistante `ultra_sandbox`.
"""
import subprocess
import sys
import tempfile
from pathlib import Path
def execute_safe(code: str, timeout: int = 10, budget_remaining=None) -> dict:
"""
Exécute du code Python dans un sous-processus isolé avec timeout.
Retourne {'success': bool, 'result': str, 'error': str|None}.
"""
with tempfile.NamedTemporaryFile(mode="w", suffix=".py", delete=False) as f:
f.write(code)
tmp_path = Path(f.name)
try:
proc = subprocess.run(
[sys.executable, str(tmp_path)],
capture_output=True,
text=True,
timeout=timeout
)
if proc.returncode == 0:
return {"success": True, "result": proc.stdout[:2000], "error": None}
return {
"success": False,
"result": "",
"error": proc.stderr[:500] or f"Code retour {proc.returncode}"
}
except subprocess.TimeoutExpired:
return {"success": False, "result": "", "error": "Timeout"}
except Exception as e:
return {"success": False, "result": "", "error": str(e)}
finally:
tmp_path.unlink(missing_ok=True)
def sandbox_info() -> dict:
return {"level": "basic", "backend": "subprocess"}
|