PersistentPythonSession#
- class ansys.common.mcp.helpers.PersistentPythonSession(python_executable: str | None = None, startup_code: str | None = None, working_directory: str | None = None)#
Maintains a persistent Python subprocess for stateful code execution.
This class allows multiple code snippets to be executed in the same Python session, preserving variables, imports, and state between executions. This is essential for LLM workflows where code is generated and executed in multiple steps.
- Parameters:
- python_executable
str, default:None Path to the Python executable to use. If
None,sys.executableis used.- startup_code
str, default:None Python code to execute when the session starts (for example, imports).
- working_directory
str, default:None Working directory for the Python process. If
None, the current directory is used.
- python_executable
Examples
Create a persistent session and execute multiple steps:
>>> session = PersistentPythonSession() >>> session.start() >>> >>> # Step 1: Define variables >>> result = session.execute("x = 10; y = 20") >>> >>> # Step 2: Use those variables >>> result = session.execute("z = x + y; print(z)") >>> print(result["stdout"]) # 30 >>> >>> session.stop()
Use with custom Python executable:
>>> session = PersistentPythonSession( ... python_executable="/path/to/venv/bin/python", ... startup_code="import numpy as np\\nimport pandas as pd", ... )
Overview#
Start the persistent Python session. |
|
Execute Python code in the persistent session. |
|
Stop the persistent Python session. |
|
Restart the persistent Python session. |
|
Check if the session is currently running. |
Import detail#
from ansys.common.mcp.helpers import PersistentPythonSession
Attribute detail#
- PersistentPythonSession.python_executable = '/home/runner/work/pyansys-common-mcp/pyansys-common-mcp/.venv/bin/python3'#
- PersistentPythonSession.startup_code = None#
- PersistentPythonSession.working_directory = None#
- PersistentPythonSession.process: subprocess.Popen | None = None#
Method detail#
- PersistentPythonSession.execute(code: str, timeout: float = 30.0) dict[str, Any]#
Execute Python code in the persistent session.
- Parameters:
- Returns:
- PersistentPythonSession.restart() dict[str, Any]#
Restart the persistent Python session.
Stops the current session (if running) and starts a new one. All session state (variables, imports) are lost except what’s recreated by
startup_code.This method is intended for manual restarts only. For example, use it when the session becomes unresponsive or when you want to reset the state. Command history and other application state should be managed at the application context level, not in the session itself.
Notes
This is a manual operation. Automatic restart on crashes is NOT implemented.
Session state is lost (including variables and non-startup imports).
The
startup_codeis re-executed on restart.Consider managing command_history at the context level for replay capability
Examples
Basic restart:
>>> session = PersistentPythonSession() >>> session.start() >>> # ... do some work ... >>> result = session.restart() >>> if result["success"]: ... print("Session restarted")
In an MCP tool with command replay:
>>> # Get context >>> ctx = get_context() >>> app_context = ctx.fastmcp._lifespan_result >>> >>> # Restart session >>> restart_result = app_context.python_session.restart() >>> >>> # Optionally replay command history >>> if restart_result["success"] and app_context.command_history: ... for cmd in app_context.command_history: ... app_context.python_session.execute(cmd)
- PersistentPythonSession.is_running() bool#
Check if the session is currently running.
- Returns:
- bool
Trueif session is running,Falseotherwise.
- PersistentPythonSession.__enter__()#
Context manager entry.
- PersistentPythonSession.__exit__(_exc_type, _exc_val, _exc_tb)#
Context manager exit.