execute_python_code
Run Python scripts within 3D Slicer to manipulate medical images, create models, or perform calculations. Assign results to __execResult
for retrieval and handle errors with detailed feedback.
Instructions
Execute Python code in 3D Slicer.
Parameters: code (str): The Python code to execute.
The code parameter is a string containing the Python code to be executed in 3D Slicer's Python environment.
The code should be executable by Python's exec()
function. To get return values, the code should assign the result to a variable named __execResult
.
Examples:
- Create a sphere model: {"tool": "execute_python_code", "arguments": {"code": "sphere = slicer.vtkMRMLModelNode(); slicer.mrmlScene.AddNode(sphere); sphere.SetName('MySphere'); __execResult = sphere.GetID()"}}
- Get the number of nodes in the current scene: {"tool": "execute_python_code", "arguments": {"code": "__execResult = len(slicer.mrmlScene.GetNodes())"}}
- Calculate 1+1: {"tool": "execute_python_code", "arguments": {"code": "__execResult = 1 + 1"}}
Returns: dict: A dictionary containing the execution result.
Examples:
- Successful execution: {"success": True, "message": 2} # Assuming the result of 1+1 is 2
- Successful execution: {"success": True, "message": "vtkMRMLScene1"} # Assuming the created sphere id is vtkMRMLScene1
- Python execution error: {"success": False, "message": "Server error: name 'slicer' is not defined"}
- Connection error: {"success": False, "message": "Connection error: ..."}
- HTTP error: {"success": False, "message": "HTTP Error 404: Not Found"}
Input Schema
Name | Required | Description | Default |
---|---|---|---|
code | Yes |