Process
Section titled “Process”class Process()Handles process and code execution within a Sandbox.
Process.__init__
Section titled “Process.__init__”def __init__(language: str, api_client: ProcessApi, http_client: httpx.Client)Initialize a new Process instance.
Arguments:
api_clientProcessApi - API client for process operations.http_client- Shared httpx.Client whose connection pool the WS upgrade reuses.
Process.exec
Section titled “Process.exec”@intercept_errors(message_prefix="Failed to execute command: ")@with_instrumentation()def exec(command: str, cwd: str | None = None, env: dict[str, str] | None = None, timeout: int | None = None) -> ExecuteResponseExecute a shell command in the Sandbox.
Arguments:
commandstr - Shell command to execute.cwdstr | None - Working directory for command execution. If not specified, uses the sandbox working directory.envdict[str, str] | None - Environment variables to set for the command.timeoutint | None - Maximum time in seconds to wait for the command to complete.
Returns:
ExecuteResponse- Command execution results containing:- exit_code: The command’s exit status
- result: Standard output from the command
- artifacts: ExecutionArtifacts object containing
stdout(same as result) andcharts(matplotlib charts metadata)
Example:
# Simple commandresponse = sandbox.process.exec("echo 'Hello'")print(response.artifacts.stdout) # Prints: Hello
# Command with working directoryresult = sandbox.process.exec("ls", cwd="workspace/src")
# Command with timeoutresult = sandbox.process.exec("sleep 10", timeout=5)Process.code_run
Section titled “Process.code_run”@with_instrumentation()def code_run(code: str, params: CodeRunParams | None = None, timeout: int | None = None) -> ExecuteResponseExecutes code in the Sandbox using the appropriate language runtime.
Arguments:
codestr - Code to execute.paramsCodeRunParams | None - Parameters for code execution.timeoutint | None - Maximum time in seconds to wait for the code to complete.
Returns:
ExecuteResponse- Code execution result containing:- exit_code: The execution’s exit status
- result: Standard output from the code
- artifacts: ExecutionArtifacts object containing
stdout(same as result) andcharts(matplotlib charts metadata)
Example:
# Run Python coderesponse = sandbox.process.code_run(''' x = 10 y = 20 print(f"Sum: {x + y}")''')print(response.artifacts.stdout) # Prints: Sum: 30Matplotlib charts are automatically detected and returned in the charts field
of the ExecutionArtifacts object.
code = '''import matplotlib.pyplot as pltimport numpy as np
x = np.linspace(0, 10, 30)y = np.sin(x)
plt.figure(figsize=(8, 5))plt.plot(x, y, 'b-', linewidth=2)plt.title('Line Chart')plt.xlabel('X-axis (seconds)')plt.ylabel('Y-axis (amplitude)')plt.grid(True)plt.show()'''
response = sandbox.process.code_run(code)chart = response.artifacts.charts[0]
print(f"Type: {chart.type}")print(f"Title: {chart.title}")if chart.type == ChartType.LINE and isinstance(chart, LineChart): print(f"X Label: {chart.x_label}") print(f"Y Label: {chart.y_label}") print(f"X Ticks: {chart.x_ticks}") print(f"X Tick Labels: {chart.x_tick_labels}") print(f"X Scale: {chart.x_scale}") print(f"Y Ticks: {chart.y_ticks}") print(f"Y Tick Labels: {chart.y_tick_labels}") print(f"Y Scale: {chart.y_scale}") print("Elements:") for element in chart.elements: print(f"Label: {element.label}") print(f"Points: {element.points}")Process.create_session
Section titled “Process.create_session”@intercept_errors(message_prefix="Failed to create session: ")@with_instrumentation()def create_session(session_id: str) -> NoneCreates a new long-running background session in the Sandbox.
Sessions are background processes that maintain state between commands, making them ideal for scenarios requiring multiple related commands or persistent environment setup. You can run long-running commands and monitor process status.
Arguments:
session_idstr - Unique identifier for the new session.
Example:
# Create a new sessionsession_id = "my-session"sandbox.process.create_session(session_id)session = sandbox.process.get_session(session_id)# Do work...sandbox.process.delete_session(session_id)Process.get_session
Section titled “Process.get_session”@intercept_errors(message_prefix="Failed to get session: ")def get_session(session_id: str) -> SessionGets a session in the Sandbox.
Arguments:
session_idstr - Unique identifier of the session to retrieve.
Returns:
Session- Session information including:- session_id: The session’s unique identifier
- commands: List of commands executed in the session
Example:
session = sandbox.process.get_session("my-session")for cmd in session.commands: print(f"Command: {cmd.command}")Process.get_entrypoint_session
Section titled “Process.get_entrypoint_session”@intercept_errors(message_prefix="Failed to get sandbox entrypoint session: ")def get_entrypoint_session() -> SessionGets the sandbox entrypoint session.
Returns:
Session- Entrypoint session information including:- session_id: The entrypoint session’s unique identifier
- commands: List of commands executed in the entrypoint session
Example:
session = sandbox.process.get_entrypoint_session()for cmd in session.commands: print(f"Command: {cmd.command}")Process.get_session_command
Section titled “Process.get_session_command”@intercept_errors(message_prefix="Failed to get session command: ")@with_instrumentation()def get_session_command(session_id: str, command_id: str) -> CommandGets information about a specific command executed in a session.
Arguments:
session_idstr - Unique identifier of the session.command_idstr - Unique identifier of the command.
Returns:
Command- Command information including:- id: The command’s unique identifier
- command: The executed command string
- exit_code: Command’s exit status (if completed)
Example:
cmd = sandbox.process.get_session_command("my-session", "cmd-123")if cmd.exit_code == 0: print(f"Command {cmd.command} completed successfully")Process.execute_session_command
Section titled “Process.execute_session_command”@intercept_errors(message_prefix="Failed to execute session command: ")@with_instrumentation()def execute_session_command( session_id: str, req: SessionExecuteRequest, timeout: int | None = None) -> SessionExecuteResponseExecutes a command in the session.
Arguments:
session_idstr - Unique identifier of the session to use.reqSessionExecuteRequest - Command execution request containing:- command: The command to execute
- run_async: Whether to execute asynchronously
Returns:
SessionExecuteResponse- Command execution results containing:- cmd_id: Unique identifier for the executed command
- output: Combined command output (stdout and stderr) (if synchronous execution)
- stdout: Standard output from the command
- stderr: Standard error from the command
- exit_code: Command exit status (if synchronous execution)
Example:
# Execute commands in sequence, maintaining statesession_id = "my-session"
# Change directoryreq = SessionExecuteRequest(command="cd /workspace")sandbox.process.execute_session_command(session_id, req)
# Create a filereq = SessionExecuteRequest(command="echo 'Hello' > test.txt")sandbox.process.execute_session_command(session_id, req)
# Read the filereq = SessionExecuteRequest(command="cat test.txt")result = sandbox.process.execute_session_command(session_id, req)print(f"Command stdout: {result.stdout}")print(f"Command stderr: {result.stderr}")Process.get_session_command_logs
Section titled “Process.get_session_command_logs”@intercept_errors(message_prefix="Failed to get session command logs: ")@with_instrumentation()def get_session_command_logs(session_id: str, command_id: str) -> SessionCommandLogsResponseGet the logs for a command executed in a session.
Arguments:
session_idstr - Unique identifier of the session.command_idstr - Unique identifier of the command.
Returns:
SessionCommandLogsResponse- Command logs including:- output: Combined command output (stdout and stderr)
- stdout: Standard output from the command
- stderr: Standard error from the command
Example:
logs = sandbox.process.get_session_command_logs( "my-session", "cmd-123")print(f"Command stdout: {logs.stdout}")print(f"Command stderr: {logs.stderr}")Process.get_session_command_logs_async
Section titled “Process.get_session_command_logs_async”@intercept_errors(message_prefix="Failed to get session command logs: ")async def get_session_command_logs_async( session_id: str, command_id: str, on_stdout: OutputHandler[str], on_stderr: OutputHandler[str]) -> NoneAsynchronously retrieves and processes the logs for a command executed in a session as they become available.
Accepts both sync and async callbacks. Async callbacks are awaited. Blocking synchronous operations inside callbacks may cause WebSocket disconnections — use async callbacks and async libraries to avoid this.
Arguments:
session_idstr - Unique identifier of the session.command_idstr - Unique identifier of the command.on_stdoutOutputHandler[str] - Callback function to handle stdout log chunks as they arrive.on_stderrOutputHandler[str] - Callback function to handle stderr log chunks as they arrive.
Example:
await sandbox.process.get_session_command_logs_async( "my-session", "cmd-123", lambda log: print(f"[STDOUT]: {log}"), lambda log: print(f"[STDERR]: {log}"),)Process.get_entrypoint_logs
Section titled “Process.get_entrypoint_logs”@intercept_errors(message_prefix="Failed to get entrypoint logs: ")@with_instrumentation()def get_entrypoint_logs() -> SessionCommandLogsResponseGet the logs for the entrypoint session.
Returns:
SessionCommandLogsResponse- Command logs including:- output: Combined command output (stdout and stderr)
- stdout: Standard output from the command
- stderr: Standard error from the command
Example:
logs = sandbox.process.get_entrypoint_logs()print(f"Command stdout: {logs.stdout}")print(f"Command stderr: {logs.stderr}")Process.get_entrypoint_logs_async
Section titled “Process.get_entrypoint_logs_async”@intercept_errors(message_prefix="Failed to get entrypoint logs: ")async def get_entrypoint_logs_async(on_stdout: OutputHandler[str], on_stderr: OutputHandler[str]) -> NoneAsynchronously retrieves and processes the logs for the entrypoint session as they become available.
Arguments:
on_stdout OutputHandler[str]: Callback function to handle stdout log chunks as they arrive. on_stderr OutputHandler[str]: Callback function to handle stderr log chunks as they arrive.
Example:
await sandbox.process.get_entrypoint_logs_async( lambda log: print(f"[STDOUT]: {log}"), lambda log: print(f"[STDERR]: {log}"),)Process.send_session_command_input
Section titled “Process.send_session_command_input”@intercept_errors(message_prefix="Failed to send session command input: ")def send_session_command_input(session_id: str, command_id: str, data: str) -> NoneSends input data to a command executed in a session.
Arguments:
session_idstr - Unique identifier of the session.command_idstr - Unique identifier of the command.datastr - Input data to send.
Process.list_sessions
Section titled “Process.list_sessions”@intercept_errors(message_prefix="Failed to list sessions: ")@with_instrumentation()def list_sessions() -> list[Session]Lists all sessions in the Sandbox.
Returns:
list[Session]- List of all sessions in the Sandbox.
Example:
sessions = sandbox.process.list_sessions()for session in sessions: print(f"Session {session.session_id}:") print(f" Commands: {len(session.commands)}")Process.delete_session
Section titled “Process.delete_session”@intercept_errors(message_prefix="Failed to delete session: ")@with_instrumentation()def delete_session(session_id: str) -> NoneTerminates and removes a session from the Sandbox, cleaning up any resources associated with it.
Arguments:
session_idstr - Unique identifier of the session to delete.
Example:
# Create and use a sessionsandbox.process.create_session("temp-session")# ... use the session ...
# Clean up when donesandbox.process.delete_session("temp-session")Process.create_pty_session
Section titled “Process.create_pty_session”@intercept_errors(message_prefix="Failed to create PTY session: ")@with_instrumentation()def create_pty_session(id: str, cwd: str | None = None, envs: dict[str, str] | None = None, pty_size: PtySize | None = None) -> PtyHandleCreates a new PTY (pseudo-terminal) session in the Sandbox.
Creates an interactive terminal session that can execute commands and handle user input. The PTY session behaves like a real terminal, supporting features like command history.
Arguments:
id- Unique identifier for the PTY session. Must be unique within the Sandbox.cwd- Working directory for the PTY session. Defaults to the sandbox’s working directory.env- Environment variables to set in the PTY session. These will be merged with the Sandbox’s default environment variables.pty_size- Terminal size configuration. Defaults to 80x24 if not specified.
Returns:
PtyHandle- Handle for managing the created PTY session. Use this to send input, receive output, resize the terminal, and manage the session lifecycle.
Raises:
DaytonaError- If the PTY session creation fails or the session ID is already in use.
Process.connect_pty_session
Section titled “Process.connect_pty_session”@intercept_errors(message_prefix="Failed to connect PTY session: ")@with_instrumentation()def connect_pty_session(session_id: str) -> PtyHandleConnects to an existing PTY session in the Sandbox.
Establishes a WebSocket connection to an existing PTY session, allowing you to interact with a previously created terminal session.
Arguments:
session_id- Unique identifier of the PTY session to connect to.
Returns:
PtyHandle- Handle for managing the connected PTY session.
Raises:
DaytonaError- If the PTY session doesn’t exist or connection fails.
Process.list_pty_sessions
Section titled “Process.list_pty_sessions”@intercept_errors(message_prefix="Failed to list PTY sessions: ")@with_instrumentation()def list_pty_sessions() -> list[PtySessionInfo]Lists all PTY sessions in the Sandbox.
Retrieves information about all PTY sessions in this Sandbox.
Returns:
list[PtySessionInfo]- List of PTY session information objects containing details about each session’s state, creation time, and configuration.
Example:
# List all PTY sessionssessions = sandbox.process.list_pty_sessions()
for session in sessions: print(f"Session ID: {session.id}") print(f"Active: {session.active}") print(f"Created: {session.created_at}")Process.get_pty_session_info
Section titled “Process.get_pty_session_info”@intercept_errors(message_prefix="Failed to get PTY session info: ")@with_instrumentation()def get_pty_session_info(session_id: str) -> PtySessionInfoGets detailed information about a specific PTY session.
Retrieves comprehensive information about a PTY session including its current state, configuration, and metadata.
Arguments:
session_id- Unique identifier of the PTY session to retrieve information for.
Returns:
PtySessionInfo- Detailed information about the PTY session including ID, state, creation time, working directory, environment variables, and more.
Raises:
DaytonaError- If the PTY session doesn’t exist.
Example:
# Get details about a specific PTY sessionsession_info = sandbox.process.get_pty_session_info("my-session")
print(f"Session ID: {session_info.id}")print(f"Active: {session_info.active}")print(f"Working Directory: {session_info.cwd}")print(f"Terminal Size: {session_info.cols}x{session_info.rows}")Process.kill_pty_session
Section titled “Process.kill_pty_session”@intercept_errors(message_prefix="Failed to kill PTY session: ")@with_instrumentation()def kill_pty_session(session_id: str) -> NoneKills a PTY session and terminates its associated process.
Forcefully terminates the PTY session and cleans up all associated resources. This will close any active connections and kill the underlying shell process. This operation is irreversible. Any unsaved work in the terminal session will be lost.
Arguments:
session_id- Unique identifier of the PTY session to kill.
Raises:
DaytonaError- If the PTY session doesn’t exist or cannot be killed.
Example:
# Kill a specific PTY sessionsandbox.process.kill_pty_session("my-session")
# Verify the session no longer existspty_sessions = sandbox.process.list_pty_sessions()for pty_session in pty_sessions: print(f"PTY session: {pty_session.id}")Process.resize_pty_session
Section titled “Process.resize_pty_session”@intercept_errors(message_prefix="Failed to resize PTY session: ")@with_instrumentation()def resize_pty_session(session_id: str, pty_size: PtySize) -> PtySessionInfoResizes a PTY session’s terminal dimensions.
Changes the terminal size of an active PTY session. This is useful when the client terminal is resized or when you need to adjust the display for different output requirements.
Arguments:
session_id- Unique identifier of the PTY session to resize.pty_size- New terminal dimensions containing the desired columns and rows.
Returns:
PtySessionInfo- Updated session information reflecting the new terminal size.
Raises:
DaytonaError- If the PTY session doesn’t exist or resize operation fails.
Example:
from daytona.common.pty import PtySize
# Resize a PTY session to a larger terminalnew_size = PtySize(rows=40, cols=150)updated_info = sandbox.process.resize_pty_session("my-session", new_size)
print(f"Terminal resized to {updated_info.cols}x{updated_info.rows}")
# You can also use the PtyHandle's resize methodpty_handle.resize(new_size)CodeRunParams
Section titled “CodeRunParams”@dataclassclass CodeRunParams()Parameters for code execution.
Attributes:
argvlist[str] | None - Command line argumentsenvdict[str, str] | None - Environment variables
SessionExecuteRequest
Section titled “SessionExecuteRequest”class SessionExecuteRequest(ApiSessionExecuteRequest, AsyncApiSessionExecuteRequest)Contains the request for executing a command in a session.
Attributes:
commandstr - The command to execute.run_asyncbool | None - Whether to execute the command asynchronously.var_asyncbool | None - Deprecated. Userun_asyncinstead.suppress_input_echobool | None - Whether to suppress input echo. Default isFalse.
ExecutionArtifacts
Section titled “ExecutionArtifacts”@dataclassclass ExecutionArtifacts()Artifacts from the command execution.
Attributes:
stdoutstr - Standard output from the command, same asresultinExecuteResponsechartslist[Chart] | None - List of chart metadata from matplotlib
ExecuteResponse
Section titled “ExecuteResponse”class ExecuteResponse(BaseModel)Response from the command execution.
Attributes:
exit_codeint - The exit code from the command executionresultstr - The output from the command executionartifactsExecutionArtifacts | None - Artifacts from the command execution
SessionExecuteResponse
Section titled “SessionExecuteResponse”class SessionExecuteResponse(ApiSessionExecuteResponse)Response from the session command execution.
Attributes:
cmd_idstr - The ID of the executed commandstdoutstr | None - The stdout from the command executionstderrstr | None - The stderr from the command executionoutputstr - The output from the command executionexit_codeint - The exit code from the command execution
SessionCommandLogsResponse
Section titled “SessionCommandLogsResponse”@dataclassclass SessionCommandLogsResponse()Response from the command logs.
Attributes:
outputstr | None - The combined output from the commandstdoutstr | None - The stdout from the commandstderrstr | None - The stderr from the command
OutputHandler
Section titled “OutputHandler”OutputHandler = Union[ Callable[[T], None], Callable[[T], Awaitable[None]],]Callback type that accepts both sync and async handlers.
Blocking synchronous operations inside handlers may cause WebSocket disconnections.