File size: 2,476 Bytes
23572e6 |
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 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 |
import subprocess
import sys
import os
import tempfile
__all__ = ['PythonSandboxTool']
class PythonSandboxTool():
dependencies = []
inputSchema = {
"name": "PythonSandboxTool",
"description": "Executes Python code in a sandbox environment.",
"parameters": {
"type": "object",
"properties": {
"code": {
"type": "string",
"description": "The Python code to execute."
}
},
"required": ["code"]
}
}
def run(self, **kwargs):
code = kwargs.get("code")
if not code:
return {"status": "error", "message": "Missing required parameter: 'code'", "output": None}
# Create a temporary directory
with tempfile.TemporaryDirectory() as tmpdir:
# Create a temporary file inside the directory
with tempfile.NamedTemporaryFile(suffix='.py', mode='w', delete=False, dir=tmpdir) as temp_file:
temp_file.write(code)
temp_file_name = temp_file.name
# Construct the command to execute the Python code
command = [sys.executable, temp_file_name]
try:
# Execute the command in a subprocess
process = subprocess.run(
command,
capture_output=True,
text=True,
timeout=10, # Timeout after 10 seconds
check=False # Do not raise an exception on non-zero exit code
)
# Get the output and error messages
stdout = process.stdout
stderr = process.stderr
# Check the return code
return_code = process.returncode
# Prepare the result
result = {
"stdout": stdout,
"stderr": stderr,
"return_code": return_code
}
# Return the result
return {"status": "success", "message": "Python code executed successfully.", "output": result}
except subprocess.TimeoutExpired:
return {"status": "error", "message": "Python code execution timed out.", "output": None}
except Exception as e:
return {"status": "error", "message": f"Python code execution failed: {str(e)}", "output": None}
|