# Process and Code Execution

Process and code execution are available through the `process` module of a sandbox. Code and commands run inside the sandbox, so untrusted or generated code executes in isolation from your application.

The `process` module covers running code snippets in Python, JavaScript, and TypeScript, with stateless execution or a persistent interpreter context, executing shell commands, and sessions: independent shells whose state persists across commands and that run long-lived processes in the background. For interactive terminal sessions, see [Pseudo Terminal (PTY)](/content/docs/en/pty.md). For real-time log streaming from long-running session commands, see [Log Streaming](/content/docs/en/log-streaming.md).

## Code execution

Daytona provides methods to execute code in sandboxes. You can run code snippets in multiple languages with support for both stateless execution and stateful interpretation with persistent contexts.

- [Run code (stateless)](#run-code-stateless): run independent code snippets where each execution starts from a clean interpreter state; inherits the sandbox language that you choose at [sandbox creation](/content/docs/en/sandboxes.md#create-sandboxes/index.html). Supports Python, JavaScript, and TypeScript.
- [Run code (stateful)](#run-code-stateful): run Python code in a persistent interpreter context with variables, imports, and state to carry across executions; available in every SDK.

### Run code (stateless)

Run code snippets in sandboxes using stateless execution. Each invocation starts from a clean interpreter, making it ideal for independent code snippets.

```python
from daytona import CodeRunParams

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

print(greet("Daytona"))
''')

print(response.result)

# Run code with argv and environment variables
response = sandbox.process.code_run(
    'import sys; print(f"Hello, {sys.argv[1]}!")',
    params=CodeRunParams(argv=["Daytona"], env={"FOO": "BAR"}),
    timeout=5,
)
print(response.result)
```

```typescript
// Run TypeScript code
let response = await sandbox.process.codeRun(`
function greet(name: string): string {
    return `Hello, ${name}!`;
}

console.log(greet("Daytona"));
`);
console.log(response.result);

// Run code with argv and environment variables
response = await sandbox.process.codeRun(
    `
    console.log(`Hello, ${process.argv[2]}!`);
    console.log(`FOO: ${process.env.FOO}`);
    `,
    { 
      argv: ["Daytona"],
      env: { FOO: "BAR" }
    }
);
console.log(response.result);

// Run code with timeout (5 seconds)
response = await sandbox.process.codeRun(
    'setTimeout(() => console.log("Done"), 2000);',
    undefined,
    5
);
console.log(response.result);
```

```ruby
# Run Python code
response = sandbox.process.code_run(code: <<~PYTHON)
  def greet(name):
      return f"Hello, {name}!"

print(greet("Daytona"))
PYTHON

puts response.result
```

```go
// Run Python code (language defaults to sandbox language)
result, err := sandbox.Process.CodeRun(ctx, `

def greet(name):
    return f"Hello, {name}!"

print(greet("Daytona"))
`)
if err != nil {
	log.Fatal(err)
}
fmt.Println(result.Result)

// Run code with environment variables
result, err = sandbox.Process.CodeRun(ctx, `import os; print(os.environ.get("FOO"))`,
	options.WithCodeRunParams(types.CodeRunParams{
		Env: map[string]string{"FOO": "BAR"},
	}),
)
if err != nil {
	log.Fatal(err)
}
fmt.Println(result.Result)

// Run code with timeout (5 seconds)
result, err = sandbox.Process.CodeRun(ctx, `import time; time.sleep(2); print("Done")`,
	options.WithCodeRunTimeout(5*time.Second),
)
if err != nil {
	log.Fatal(err)
}
fmt.Println(result.Result)
```

```java
import io.daytona.sdk.model.ExecuteResponse;
import java.util.Map;

// Run code (stateless; language matches the sandbox image)
ExecuteResponse response = sandbox.process.codeRun(
    """
    def greet(name):
        return f"Hello, {name}!"

print(greet("Daytona"))
    """
);
System.out.println(response.getResult());

// Run code with environment variables and timeout (seconds)
response = sandbox.process.codeRun(
    "import os; print('FOO:', os.environ.get('FOO'))",
    Map.of("FOO", "BAR"),
    null
);
System.out.println(response.getResult());

response = sandbox.process.codeRun(
    "import time; time.sleep(2); print(\"Done\")",
    null,
    5
);
System.out.println(response.getResult());
```

```bash
curl 'https://proxy.app.daytona.io/toolbox/{sandboxId}/process/code-run' \
  --request POST \
  --header 'Content-Type: application/json' \
  --data '{
  "code": "def greet(name):\n    return f\"Hello, {name}!\"\n\nprint(greet(\"Daytona\"))",
  "language": "python",
  "envs": {
    "FOO": "BAR"
  },
  "timeout": 5
}'
```

### Artifacts

Stateless `code_run` responses can include an `artifacts` field. When your code produces matplotlib charts, the SDK strips chart metadata from `result` and returns it in the `artifacts.charts` field.

```python
code = '''
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, 30)
plt.plot(x, np.sin(x))
plt.title("Sine wave")
plt.show()
'''

response = sandbox.process.code_run(code)
if response.artifacts and response.artifacts.charts:
    chart = response.artifacts.charts[0]
    print(chart.type, chart.title)
```

```typescript
const response = await sandbox.process.codeRun(`
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, 30)
plt.plot(x, np.sin(x))
plt.title("Sine wave")
plt.show()
`)

if (response.artifacts?.charts?.length) {
    const chart = response.artifacts.charts[0]
    console.log(chart.type, chart.title)
}
```

### Run code (stateful)

Run Python code with persistent state using the code interpreter. You can maintain variables and imports between calls, create isolated contexts with optional working directories, list active contexts, and stream stdout, stderr, and errors via callbacks.

```python
from daytona import Daytona, OutputMessage, ExecutionError

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}")

daytona = Daytona()
sandbox = daytona.create()

# Shared default context
sandbox.code_interpreter.run_code(
    "counter = 1\nprint(f'Counter initialized at {counter}')",
    on_stdout=handle_stdout,
    on_stderr=handle_stderr,
    on_error=handle_error,
    timeout=60,
)

# Isolated context with working directory
ctx = sandbox.code_interpreter.create_context(cwd="workspace/src")
try:
    sandbox.code_interpreter.run_code(
        "value = 'stored in ctx'",
        context=ctx,
        envs={"DEBUG": "1"},
    )
    sandbox.code_interpreter.run_code(
        "print(value)",
        context=ctx,
        on_stdout=handle_stdout,
    )
finally:
    sandbox.code_interpreter.delete_context(ctx)

# List user-created contexts
for context in sandbox.code_interpreter.list_contexts():
    print(context.id, context.cwd)
```

```typescript
import { Daytona } from '@daytona/sdk'

const daytona = new Daytona()

async function main() {
    const sandbox = await daytona.create()

// Shared default context
    await sandbox.codeInterpreter.runCode(
`counter = 1
print(f'Counter initialized at {counter}')`,
        {
            onStdout: (msg) => process.stdout.write(`[STDOUT] ${msg.output}`),
            onStderr: (msg) => process.stdout.write(`[STDERR] ${msg.output}`),
            timeout: 60,
        },
    )

// Isolated context with working directory
    const ctx = await sandbox.codeInterpreter.createContext('workspace/src')
    try {
        await sandbox.codeInterpreter.runCode(
            `value = 'stored in ctx'`,
            { context: ctx, envs: { DEBUG: '1' } },
        )
        await sandbox.codeInterpreter.runCode(
            `print(value)`,
            { context: ctx, onStdout: (msg) => process.stdout.write(`[STDOUT] ${msg.output}`) },
        )
    } finally {
        await sandbox.codeInterpreter.deleteContext(ctx)
    }

// List user-created contexts
    const contexts = await sandbox.codeInterpreter.listContexts()
    for (const context of contexts) {
        console.log(context.id, context.cwd)
    }
}

main()
```

```ruby
require 'daytona'

daytona = Daytona::Daytona.new
sandbox = daytona.create

# Shared default context
sandbox.code_interpreter.run_code(
  <<~PYTHON,
  counter = 1
  print(f'Counter initialized at {counter}')
  PYTHON
  on_stdout: ->(msg) { print "[STDOUT] #{msg.output}" }
)

# Isolated context
ctx = sandbox.code_interpreter.create_context
begin
  sandbox.code_interpreter.run_code("value = 'stored in ctx'", context: ctx)
  sandbox.code_interpreter.run_code(
    "print(value)",
    context: ctx,
    on_stdout: ->(msg) { print "[STDOUT] #{msg.output}" }
  )
ensure
  sandbox.code_interpreter.delete_context(ctx)
end
```

```go
// Shared default context
channels, err := sandbox.CodeInterpreter.RunCode(ctx,
	"counter = 1\nprint(f'Counter initialized at {counter}')",
)
if err != nil {
	log.Fatal(err)
}
for msg := range channels.Stdout {
	fmt.Printf("[STDOUT] %s\n", msg.Text)
}

// Isolated context
cwd := "workspace/src"
ctxInfo, err := sandbox.CodeInterpreter.CreateContext(ctx, &cwd)
if err != nil {
	log.Fatal(err)
}
contextID := ctxInfo["id"].(string)

channels, err = sandbox.CodeInterpreter.RunCode(ctx,
	"value = 'stored in ctx'",
	options.WithCustomContext(contextID),
	options.WithEnv(map[string]string{"DEBUG": "1"}),
)
if err != nil {
	log.Fatal(err)
}
for msg := range channels.Stdout {
	fmt.Printf("[STDOUT] %s\n", msg.Text)
}

// List user-created contexts
contexts, err := sandbox.CodeInterpreter.ListContexts(ctx)
if err != nil {
	log.Fatal(err)
}
for _, context := range contexts {
	fmt.Println(context["id"], context["cwd"])
}

// Clean up context
err = sandbox.CodeInterpreter.DeleteContext(ctx, contextID)
if err != nil {
	log.Fatal(err)
}
```

```java
import io.daytona.sdk.model.Session;

// Clean up session
String sessionId = "long-running-cmd";
try {
    sandbox.process.createSession(sessionId);
    Session session = sandbox.process.getSession(sessionId);
    // Do work...
} finally {
    sandbox.process.deleteSession(sessionId);
}
```

```bash
# Create session
curl 'https://proxy.app.daytona.io/toolbox/{sandboxId}/process/session' \
  --request POST \
  --header 'Content-Type: application/json' \
  --data '{"sessionId": "interactive-session"}'

# Execute session command
curl 'https://proxy.app.daytona.io/toolbox/{sandboxId}/process/session/{sessionId}/exec' \
  --request POST \
  --header 'Content-Type: application/json' \
  --data '{
  "command": "pip uninstall requests",
  "runAsync": true
}'

# Send input to command
curl 'https://proxy.app.daytona.io/toolbox/{sandboxId}/process/session/{sessionId}/command/{commandId}/input' \
  --request POST \
  --header 'Content-Type: application/json' \
  --data '{
  "data": "y"
}'

# Get command logs (append ?follow=true for WebSocket streaming)
curl 'https://proxy.app.daytona.io/toolbox/{sandboxId}/process/session/{sessionId}/command/{commandId}/logs'
```
