Process and Code Execution | Daytona

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. For real-time log streaming from long-running session commands, see Log Streaming.

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 snippets in sandboxes using stateless execution. Each invocation starts from a clean interpreter, making it ideal for independent code snippets.

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)
// 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);
# Run Python code

response = sandbox.process.code_run(code: <<~PYTHON)

def greet(name):

return f"Hello, {name}!"

print(greet("Daytona"))

PYTHON

puts response.result
// 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)
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());
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.

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)
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.

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)
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()
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
// 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)
}
// 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);
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.

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}")
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);
    }
}
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
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)
}
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());
}
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
# }