33 lines
1.2 KiB
Python
33 lines
1.2 KiB
Python
import docker
|
|
from typing import Dict, Any
|
|
|
|
class DockerSandboxTool:
|
|
def __init__(self):
|
|
try:
|
|
self.client = docker.from_env()
|
|
except Exception as e:
|
|
self.client = None
|
|
print(f"Failed to initialize Docker client: {e}")
|
|
|
|
def run_code(self, code: str, image: str = "python:3.9-slim") -> Dict[str, Any]:
|
|
if not self.client:
|
|
return {"error": "Docker client not initialized"}
|
|
|
|
try:
|
|
# Simple python code runner in a container
|
|
container = self.client.containers.run(
|
|
image,
|
|
command=["python", "-c", code],
|
|
remove=True,
|
|
detach=False,
|
|
stdout=True,
|
|
stderr=True
|
|
)
|
|
# Depending on python version, container returns bytes directly
|
|
output = container.decode("utf-8") if isinstance(container, bytes) else container
|
|
return {"status": "success", "output": output}
|
|
except docker.errors.ContainerError as e:
|
|
return {"status": "error", "output": e.stderr.decode("utf-8")}
|
|
except Exception as e:
|
|
return {"status": "error", "error": str(e)}
|