Execute agent-generated code safely in subprocess or Docker sandbox with timeouts and resource limits.
Code Execution Agents
import subprocess, tempfile, os
def safe_execute_python(code: str, timeout: int = 15) -> dict:
"""Execute Python in isolated subprocess with timeout."""
with tempfile.NamedTemporaryFile(suffix=".py", delete=False, mode="w") as f:
f.write(code)
tmp_path = f.name
try:
result = subprocess.run(
["python3", tmp_path],
capture_output=True, text=True,
timeout=timeout,
env={**os.environ, "PYTHONPATH":""}
)
return {
"stdout": result.stdout,
"stderr": result.stderr,
"returncode": result.returncode
}
except subprocess.TimeoutExpired:
return {"error": "Execution timed out", "stdout":"","stderr":""}
finally:
os.unlink(tmp_path)
# Docker sandbox (more secure)
import docker
client = docker.from_env()
def docker_execute(code: str) -> str:
result = client.containers.run(
"python:3.12-slim",
f'python3 -c "{code}"',
remove=True, network_disabled=True,
mem_limit="128m", cpu_period=100000, cpu_quota=50000
)
return result.decode()