# 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/index.html). For real-time log streaming from long-running session commands, see [Log Streaming](/content/docs/en/log-streaming/index.html).

## 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)](/content/docs/en/process-code-execution/#run-code-stateless/index.html): 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#create-sandboxes/index.html). Supports Python, JavaScript, and TypeScript.
- [Run code (stateful)](/content/docs/en/process-code-execution/#run-code-stateful/index.html): 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](/content/docs/en/process-code-execution/#tab-panel-1108/index.html)
- [TypeScript](/content/docs/en/process-code-execution/#tab-panel-1109/index.html)
- [Ruby](/content/docs/en/process-code-execution/#tab-panel-1110/index.html)
- [Go](/content/docs/en/process-code-execution/#tab-panel-1111/index.html)
- [Java](/content/docs/en/process-code-execution/#tab-panel-1112/index.html)
- [API](/content/docs/en/process-code-execution/#tab-panel-1113/index.html)

```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);
```

```python
# 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());
```

```shell
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](/content/docs/en/process-code-execution/#tab-panel-1114/index.html)
- [TypeScript](/content/docs/en/process-code-execution/#tab-panel-1115/index.html)

```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](/content/docs/en/process-code-execution/#tab-panel-1116/index.html)
- [TypeScript](/content/docs/en/process-code-execution/#tab-panel-1117/index.html)
- [Ruby](/content/docs/en/process-code-execution/#tab-panel-1118/index.html)
- [Go](/content/docs/en/process-code-execution/#tab-panel-1119/index.html)
- [Java](/content/docs/en/process-code-execution/#tab-panel-1120/index.html)
- [API](/content/docs/en/process-code-execution/#tab-panel-1121/index.html)

```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
// Shared default context

Session session = sandbox.process.createSession(sessionId);

sandbox.process.runCode(

"counter = 1\nprint(f'Counter initialized at {counter}')",
    new RunCodeOptions()
        .setOnStdout(chunk -> System.out.print("[STDOUT] " + chunk))
        .setOnStderr(chunk -> System.out.print("[STDERR] " + chunk))
        .setTimeout(60)
);

// Clean up
    sandbox.process.deleteSession(sessionId);
```

```shell
curl 'https://proxy.app.daytona.io/toolbox/{sandboxId}/process/session' \
  --request POST \
  --header 'Content-Type: application/json' \
  --data '{"sessionId": "long-running-cmd"}'

curl 'https://proxy.app.daytona.io/toolbox/{sandboxId}/process/session/{sessionId}' \
  --request DELETE
```

## Error handling

Handle process exceptions properly, log error details for debugging, and use try-catch blocks for error handling.

- [Python](/content/docs/en/process-code-execution/#tab-panel-1159/index.html)
- [TypeScript](/content/docs/en/process-code-execution/#tab-panel-1160/index.html)
- [Ruby](/content/docs/en/process-code-execution/#tab-panel-1161/index.html)
- [Go](/content/docs/en/process-code-execution/#tab-panel-1162/index.html)
- [Java](/content/docs/en/process-code-execution/#tab-panel-1163/index.html)
- [API](/content/docs/en/process-code-execution/#tab-panel-1164/index.html)

```python
from daytona import DaytonaError

try:

response = sandbox.process.code_run("invalid python code")

if response.exit_code != 0:

print(f"Exit code: {response.exit_code}")

print(f"Error output: {response.result}")

except DaytonaError as e:

print(f"Execution failed: {e}")
```

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

try {

const response = await sandbox.process.codeRun("invalid typescript code");

if (response.exitCode !== 0) {

console.error("Exit code:", response.exitCode);

console.error("Error output:", response.result);

}
} catch (e) {
    if (e instanceof DaytonaError) {
        console.error("Execution failed:", e);
    }
}
```

```ruby
begin
  response = sandbox.process.code_run(code: 'invalid python code')
  if response.exit_code != 0
    puts "Exit code: #{response.exit_code}"
    puts "Error output: #{response.result}"
  end
rescue StandardError => e
  puts "Execution failed: #{e}"
end
```

```go
result, err := sandbox.Process.CodeRun(ctx, "invalid python code")

if err != nil {

fmt.Println("Execution failed:", err)
}

if result != nil && result.ExitCode != 0 {

fmt.Println("Exit code:", result.ExitCode)

fmt.Println("Error output:", result.Result)
}
```

```java
import io.daytona.sdk.exception.DaytonaException;
import io.daytona.sdk.model.ExecuteResponse;

try {
    ExecuteResponse response = sandbox.process.codeRun("invalid python code");
    if (response.getExitCode() != null && response.getExitCode() != 0) {
        System.out.println("Exit code: " + response.getExitCode());
        System.out.println("Error output: " + response.getResult());
    }
} catch (DaytonaException e) {
    System.out.println("Execution failed: " + e.getMessage());
}
```

```shell
curl 'https://proxy.app.daytona.io/toolbox/{sandboxId}/process/execute' \
  --request POST \
  --header 'Content-Type: application/json' \
  --data '{"command": "python3 -c \"invalid python code\""}'
# Response includes:
# {
#   "result": "",
#   "exitCode": 1
# }
```
