Skip to main content
This example demonstrates various ways to execute code in Daytona sandboxes, from simple commands to stateful code interpretation.

What You’ll Learn

  • Running code directly with code_run()
  • Executing OS commands with exec()
  • Using execution sessions for stateful operations
  • Streaming command output asynchronously
  • Using the stateful code interpreter
  • Context isolation and management
  • Timeout handling

Complete Example

from daytona import (
    CreateSandboxFromImageParams,
    Daytona,
    DaytonaTimeoutError,
    ExecutionError,
    OutputMessage,
    Resources,
    Sandbox,
)


def main():
    daytona = Daytona()

    params = CreateSandboxFromImageParams(
        image="python:3.9.23-slim",
        language="python",
        resources=Resources(
            cpu=1,
            memory=1,
            disk=3,
        ),
    )
    sandbox = daytona.create(params, timeout=150, on_snapshot_create_logs=print)

    # Run the code securely inside the sandbox
    response = sandbox.process.code_run('print("Hello World!")')
    if response.exit_code != 0:
        print(f"Error: {response.exit_code} {response.result}")
    else:
        print(response.result)

    # Execute an os command in the sandbox
    response = sandbox.process.exec('echo "Hello World from exec!"', timeout=10)
    if response.exit_code != 0:
        print(f"Error: {response.exit_code} {response.result}")
    else:
        print(response.result)

    stateful_code_interpreter(sandbox)

    daytona.delete(sandbox)


def stateful_code_interpreter(sandbox: Sandbox):
    def handle_stdout(message: OutputMessage):
        print(f"[STDOUT] {message.output}")

    def handle_stderr(message: OutputMessage):
        print(f"[STDERR] {message.output}")

    def handle_error(error: ExecutionError):
        print(f"[ERROR] {error.name}: {error.value}\n{error.traceback}")

    print("\n" + "=" * 60)
    print("Stateful Code Interpreter")
    print("=" * 60)

    print("=" * 10 + " Statefulness in the default context " + "=" * 10)
    result = sandbox.code_interpreter.run_code("counter = 1\nprint(f'Initialized counter = {counter}')")
    print(f"[STDOUT] {result.stdout}")

    result = sandbox.code_interpreter.run_code(
        "counter += 1\nprint(f'Counter after second call = {counter}')",
        on_stdout=handle_stdout,
        on_stderr=handle_stderr,
        on_error=handle_error,
    )

    print("=" * 10 + " Context isolation " + "=" * 10)
    ctx = sandbox.code_interpreter.create_context()
    try:
        ctx_result = sandbox.code_interpreter.run_code(
            "value = 'stored in isolated context'\nprint(f'Isolated context value: {value}')",
            context=ctx,
            on_stdout=handle_stdout,
            on_stderr=handle_stderr,
            on_error=handle_error,
        )

        print("-" * 3 + " Print value from same context " + "-" * 3)
        ctx_result = sandbox.code_interpreter.run_code(
            "print(f'Value still available: {value}')",
            context=ctx,
        )
        print(f"[STDOUT] {ctx_result.stdout}")

        print("-" * 3 + " Print value from different context " + "-" * 3)
        _ = sandbox.code_interpreter.run_code(
            "print(value)",
            on_stdout=handle_stdout,
            on_stderr=handle_stderr,
            on_error=handle_error,
        )
    finally:
        sandbox.code_interpreter.delete_context(ctx)

    print("=" * 10 + " Timeout handling " + "=" * 10)
    try:
        code = """
import time
print('Starting long running task...')
time.sleep(5)
print('Finished!')
"""
        _ = sandbox.code_interpreter.run_code(
            code,
            timeout=1,
            on_stdout=handle_stdout,
            on_stderr=handle_stderr,
            on_error=handle_error,
        )
    except DaytonaTimeoutError as exc:
        print(f"Timed out as expected: {exc}")


if __name__ == "__main__":
    main()

Expected Output

Creating sandbox...
✓ Created sandbox: sandbox-abc123 (ID: abc123)

Hello World!
Hello World from exec!

============================================================
Stateful Code Interpreter
============================================================
========== Statefulness in the default context ==========
[STDOUT] Initialized counter = 1
[STDOUT] Counter after second call = 2
========== Context isolation ==========
[STDOUT] Isolated context value: stored in isolated context
--- Print value from same context ---
[STDOUT] Value still available: stored in isolated context
--- Print value from different context ---
[ERROR] NameError: name 'value' is not defined
========== Timeout handling ==========
[STDOUT] Starting long running task...
Timed out as expected: Code execution timed out after 1 seconds

Key Concepts

Basic Code Execution

Run code directly in the sandbox:
# Run Python code
response = sandbox.process.code_run('print("Hello")')
print(response.result)

# Execute OS command
response = sandbox.process.exec('ls -la', timeout=10)
print(response.result)

Execution Sessions

Maintain state across multiple commands:
// Create session
await sandbox.process.createSession('my-session')

// Execute commands in session
await sandbox.process.executeSessionCommand('my-session', {
  command: 'export MY_VAR=hello'
})

const result = await sandbox.process.executeSessionCommand('my-session', {
  command: 'echo $MY_VAR'
})
console.log(result.stdout) // "hello"

// Delete session
await sandbox.process.deleteSession('my-session')

Stateful Code Interpreter

The code interpreter maintains state between executions:
# First execution - set variable
result1 = sandbox.code_interpreter.run_code(
    "counter = 1\nprint(counter)"
)

# Second execution - variable persists
result2 = sandbox.code_interpreter.run_code(
    "counter += 1\nprint(counter)"
)
# Output: 2

Context Isolation

Create isolated execution contexts:
# Create isolated context
ctx = sandbox.code_interpreter.create_context()

# Run code in context
sandbox.code_interpreter.run_code(
    "secret = 'isolated'",
    context=ctx
)

# Variable not available in default context
sandbox.code_interpreter.run_code(
    "print(secret)"  # NameError!
)

# But available in same context
sandbox.code_interpreter.run_code(
    "print(secret)",  # Works!
    context=ctx
)

# Clean up
sandbox.code_interpreter.delete_context(ctx)

Streaming Output

Handle output in real-time:
def handle_stdout(msg: OutputMessage):
    print(f"[STDOUT] {msg.output}")

def handle_stderr(msg: OutputMessage):
    print(f"[STDERR] {msg.output}")

def handle_error(err: ExecutionError):
    print(f"[ERROR] {err.name}: {err.value}")

sandbox.code_interpreter.run_code(
    code,
    on_stdout=handle_stdout,
    on_stderr=handle_stderr,
    on_error=handle_error
)

Timeout Handling

Set execution timeouts:
try:
    sandbox.code_interpreter.run_code(
        "import time\ntime.sleep(10)",
        timeout=2  # seconds
    )
except DaytonaTimeoutError:
    print("Execution timed out")

Common Patterns

Data Processing Pipeline

# Load data
sandbox.code_interpreter.run_code("""
import json
data = [1, 2, 3, 4, 5]
""")

# Process
sandbox.code_interpreter.run_code("""
processed = [x * 2 for x in data]
""")

# Export
result = sandbox.code_interpreter.run_code("""
print(json.dumps(processed))
""")
output = json.loads(result.stdout)

Interactive Sessions

// Create session for user
const sessionId = `user-${userId}`
await sandbox.process.createSession(sessionId)

// Execute user commands
const result = await sandbox.process.executeSessionCommand(sessionId, {
  command: userInput,
  runAsync: true
})

// Stream logs
await sandbox.process.getSessionCommandLogs(
  sessionId,
  result.cmdId,
  (stdout) => sendToUser(stdout),
  (stderr) => sendErrorToUser(stderr)
)

Best Practices

Use contexts for isolation: When running untrusted code or multiple independent executions, use separate contexts to prevent interference.
Always set timeouts: Protect against infinite loops and long-running operations by setting appropriate timeouts.
Clean up resources: Delete contexts and sessions when done to free up resources in the sandbox.

Next Steps

File Operations

Work with files in sandboxes

Auto Lifecycle

Configure automatic policies

Build docs developers (and LLMs) love