Skip to content

Process and Code Execution

View as Markdown

The Daytona SDK provides powerful process and code execution capabilities through the process module in Sandboxes. This guide covers all available process operations and best practices.

Code Execution

Daytona SDK supports both stateless and stateful code execution flows. Stateless runs use the process module and supports multiple languages (Python, TypeScript, JavaScript). The stateful code interpreter keeps variables and imports between calls and currently supports only Python.

Stateless Execution

Use stateless execution when each snippet is independent. Every invocation starts from a clean interpreter.

# Run Python code
response = sandbox.process.code_run('''
def greet(name):
return f"Hello, {name}!"
print(greet("Daytona"))
''')
print(response.result)

See: code_run (Python SDK), codeRun (TypeScript SDK)

Stateful Code Interpreter

When you need to persist variables, imports between calls, use the Sandbox code interpreter. It offers:

  • A shared default context that keeps state between calls.
  • The ability to create/delete isolated contexts for specific workflows.
  • Per-call environment variables and timeout controls.
from daytona import Daytona, OutputMessage
def handle_stdout(message: OutputMessage):
print(f"[STDOUT] {message.output}")
daytona = Daytona()
sandbox = daytona.create()
# Shared default context
result = sandbox.code_interpreter.run_code(
"counter = 1\nprint(f'Counter initialized at {counter}')",
on_stdout=handle_stdout,
)
# Isolated context
ctx = sandbox.code_interpreter.create_context()
try:
sandbox.code_interpreter.run_code(
"value = 'stored in ctx'",
context=ctx,
)
sandbox.code_interpreter.run_code(
"print(value)",
context=ctx,
on_stdout=handle_stdout,
)
finally:
sandbox.code_interpreter.delete_context(ctx)

See: code_interpreter (Python SDK) and codeInterpreter (TypeScript SDK)

Process Execution

Daytona SDK provides an option to execute shell commands and manage background processes in Sandboxes. The workDir for executing defaults to the current Sandbox working directory. Uses the WORKDIR specified in the Dockerfile if present, or falling back to the user’s home directory if not - e.g. workspace/repo implies /my-work-dir/workspace/repo, but you can override it with an absolute path (by starting the path with /).

Running Commands

Daytona SDK provides an option to execute shell commands in Python and TypeScript. You can run commands with input, timeout, and environment variables.

# Execute any shell command
response = sandbox.process.exec("ls -la")
print(response.result)
# Setting a working directory and a timeout
response = sandbox.process.exec("sleep 3", cwd="workspace/src", timeout=5)
print(response.result)
# Passing environment variables
response = sandbox.process.exec("echo $CUSTOM_SECRET", env={
"CUSTOM_SECRET": "DAYTONA"
}
)
print(response.result)

See: exec (Python SDK), executeCommand (TypeScript SDK)

Sessions (Background Processes)

Daytona SDK provides an option to start, stop, and manage background process sessions in Sandboxes. You can run long-running commands, monitor process status, and list all running processes.

Managing Long-Running Processes

Daytona SDK provides an option to start and stop background processes. You can run long-running commands and monitor process status.

# Check session's executed commands
session = sandbox.process.get_session(session_id)
print(f"Session {process_id}:")
for command in session.commands:
print(f"Command: {command.command}, Exit Code: {command.exit_code}")
# List all running sessions
sessions = sandbox.process.list_sessions()
for session in sessions:
print(f"PID: {session.id}, Commands: {session.commands}")

See: get_session (Python SDK), list_sessions (Python SDK), getSession (TypeScript SDK), listSessions (TypeScript SDK)

Best Practices

Use the following best practices when working with process and code execution in Daytona SDK.

Resource Management

The following best practices apply to managing resources when executing processes:

  1. Use sessions for long-running operations
  2. Clean up sessions after execution
  3. Handle session exceptions properly
# Python - Clean up session
session_id = "long-running-cmd"
try:
sandbox.process.create_session(session_id)
session = sandbox.process.get_session(session_id)
# Do work...
finally:
sandbox.process.delete_session(session.session_id)

See: create_session (Python SDK), delete_session (Python SDK), createSession (TypeScript SDK), deleteSession (TypeScript SDK)

Error Handling

The following best practices apply to error handling when executing processes:

  • Handle process exceptions properly
  • Log error details for debugging
  • Use try-catch blocks for error handling
try:
response = sandbox.process.code_run("invalid python code")
except ProcessExecutionError as e:
print(f"Execution failed: {e}")
print(f"Exit code: {e.exit_code}")
print(f"Error output: {e.stderr}")

Common Issues

To troubleshoot common issues related to process and code execution, refer to the following table:

IssueSolutions
Process Execution Failed• Check command syntax
• Verify required dependencies
• Ensure sufficient permissions
Process Timeout• Adjust timeout settings
• Optimize long-running operations
• Consider using background processes
Resource Limits• Monitor process memory usage
• Handle process cleanup properly
• Use appropriate resource constraints