run_python_file
Execute a Python file with specified arguments and environment, returning the result for seamless script integration and automation within the MCP Python Interpreter.
Instructions
Execute a Python file and return the result.
Args:
file_path: Path to the Python file to execute (relative to working directory or absolute if system access is enabled)
environment: Name of the Python environment to use (default if custom path provided, otherwise system)
arguments: List of command-line arguments to pass to the script
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| arguments | No | ||
| environment | No | default | |
| file_path | Yes |
Implementation Reference
- mcp_python_interpreter/server.py:627-682 (handler)The handler function for the 'run_python_file' tool. Decorated with @mcp.tool() which registers it in the MCP server. Executes the specified Python file using subprocess in the chosen Python environment, with support for arguments and timeout.@mcp.tool() async def run_python_file( file_path: str, environment: str = "default", arguments: Optional[List[str]] = None, timeout: int = 300 ) -> str: """ Execute a Python file (always uses subprocess for file execution). Args: file_path: Path to the Python file to execute environment: Name of the Python environment to use arguments: List of command-line arguments to pass to the script timeout: Maximum execution time in seconds (default: 300) """ path = Path(file_path) if path.is_absolute(): if not is_path_allowed(path): return f"Access denied: Can only run files in working directory: {WORKING_DIR}" else: path = WORKING_DIR / path if not path.exists(): return f"File '{path}' not found." environments = get_python_environments() if environment == "default" and not any(e["name"] == "default" for e in environments): environment = "system" env = next((e for e in environments if e["name"] == environment), None) if not env: return f"Environment '{environment}' not found. Available: {', '.join(e['name'] for e in environments)}" cmd = [env["path"], str(path)] if arguments: cmd.extend(arguments) result = await run_subprocess_async(cmd, cwd=str(WORKING_DIR), timeout=timeout) output = f"Execution of '{path}' in '{environment}' environment:\n\n" if result["status"] == 0: output += "--- Output ---\n" output += result["stdout"] if result["stdout"] else "(No output)\n" else: output += f"--- Error (status code: {result['status']}) ---\n" output += result["stderr"] if result["stderr"] else "(No error message)\n" if result["stdout"]: output += "\n--- Output ---\n" output += result["stdout"] return output