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

Expected Output

Key Concepts

Basic Code Execution

Run code directly in the sandbox:

Execution Sessions

Maintain state across multiple commands:

Stateful Code Interpreter

The code interpreter maintains state between executions:

Context Isolation

Create isolated execution contexts:

Streaming Output

Handle output in real-time:

Timeout Handling

Set execution timeouts:

Common Patterns

Data Processing Pipeline

Interactive Sessions

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