Spaces:
Running
Running
Kunal Pai
commited on
Commit
·
23572e6
1
Parent(s):
608ee17
Add PythonSandboxTool for executing Python code in a sandbox environment
Browse files
src/tools/user_tools/python_sandbox_tool.py
ADDED
@@ -0,0 +1,74 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
|
2 |
+
import subprocess
|
3 |
+
import sys
|
4 |
+
import os
|
5 |
+
import tempfile
|
6 |
+
|
7 |
+
__all__ = ['PythonSandboxTool']
|
8 |
+
|
9 |
+
class PythonSandboxTool():
|
10 |
+
dependencies = []
|
11 |
+
|
12 |
+
inputSchema = {
|
13 |
+
"name": "PythonSandboxTool",
|
14 |
+
"description": "Executes Python code in a sandbox environment.",
|
15 |
+
"parameters": {
|
16 |
+
"type": "object",
|
17 |
+
"properties": {
|
18 |
+
"code": {
|
19 |
+
"type": "string",
|
20 |
+
"description": "The Python code to execute."
|
21 |
+
}
|
22 |
+
},
|
23 |
+
"required": ["code"]
|
24 |
+
}
|
25 |
+
}
|
26 |
+
|
27 |
+
def run(self, **kwargs):
|
28 |
+
code = kwargs.get("code")
|
29 |
+
if not code:
|
30 |
+
return {"status": "error", "message": "Missing required parameter: 'code'", "output": None}
|
31 |
+
|
32 |
+
# Create a temporary directory
|
33 |
+
with tempfile.TemporaryDirectory() as tmpdir:
|
34 |
+
# Create a temporary file inside the directory
|
35 |
+
with tempfile.NamedTemporaryFile(suffix='.py', mode='w', delete=False, dir=tmpdir) as temp_file:
|
36 |
+
temp_file.write(code)
|
37 |
+
temp_file_name = temp_file.name
|
38 |
+
|
39 |
+
# Construct the command to execute the Python code
|
40 |
+
command = [sys.executable, temp_file_name]
|
41 |
+
|
42 |
+
try:
|
43 |
+
# Execute the command in a subprocess
|
44 |
+
process = subprocess.run(
|
45 |
+
command,
|
46 |
+
capture_output=True,
|
47 |
+
text=True,
|
48 |
+
timeout=10, # Timeout after 10 seconds
|
49 |
+
check=False # Do not raise an exception on non-zero exit code
|
50 |
+
)
|
51 |
+
|
52 |
+
# Get the output and error messages
|
53 |
+
stdout = process.stdout
|
54 |
+
stderr = process.stderr
|
55 |
+
|
56 |
+
# Check the return code
|
57 |
+
return_code = process.returncode
|
58 |
+
|
59 |
+
# Prepare the result
|
60 |
+
result = {
|
61 |
+
"stdout": stdout,
|
62 |
+
"stderr": stderr,
|
63 |
+
"return_code": return_code
|
64 |
+
}
|
65 |
+
|
66 |
+
# Return the result
|
67 |
+
return {"status": "success", "message": "Python code executed successfully.", "output": result}
|
68 |
+
|
69 |
+
except subprocess.TimeoutExpired:
|
70 |
+
return {"status": "error", "message": "Python code execution timed out.", "output": None}
|
71 |
+
except Exception as e:
|
72 |
+
return {"status": "error", "message": f"Python code execution failed: {str(e)}", "output": None}
|
73 |
+
|
74 |
+
|