Process and Code Execution
The Daytona SDK provides powerful process and code execution capabilities through the process module in Sandboxes. This guide covers all available process operations and best practices.
Code Execution
Daytona SDK supports both stateless and stateful code execution flows. Stateless runs use the process module and
supports multiple languages (Python, TypeScript, JavaScript). The stateful code interpreter keeps variables and imports
between calls and currently supports only Python.
Stateless Execution
Use stateless execution when each snippet is independent. Every invocation starts from a clean interpreter.
# Run Python coderesponse = sandbox.process.code_run('''def greet(name): return f"Hello, {name}!"
print(greet("Daytona"))''')
print(response.result)// Run TypeScript codelet 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 variablesresponse = 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 timeoutresponse = await sandbox.process.codeRun( 'setTimeout(() => console.log("Done"), 2000);', undefined, 5000);console.log(response.result);See: code_run (Python SDK), codeRun (TypeScript SDK)
Stateful Code Interpreter
When you need to persist variables, imports between calls, use the Sandbox code interpreter. It offers:
- A shared default context that keeps state between calls.
- The ability to create/delete isolated contexts for specific workflows.
- Per-call environment variables and timeout controls.
from daytona import Daytona, OutputMessage
def handle_stdout(message: OutputMessage): print(f"[STDOUT] {message.output}")
daytona = Daytona()sandbox = daytona.create()
# Shared default contextresult = sandbox.code_interpreter.run_code( "counter = 1\nprint(f'Counter initialized at {counter}')", on_stdout=handle_stdout,)
# Isolated contextctx = sandbox.code_interpreter.create_context()try: sandbox.code_interpreter.run_code( "value = 'stored in ctx'", context=ctx, ) sandbox.code_interpreter.run_code( "print(value)", context=ctx, on_stdout=handle_stdout, )finally: sandbox.code_interpreter.delete_context(ctx)import { Daytona } from '@daytonaio/sdk'
const daytona = new Daytona()
async function main() { const sandbox = await daytona.create()
// Shared default context await sandbox.codeInterpreter.runCode(`counter = 1print(f'Counter initialized at {counter}')`, { onStdout: (msg) => process.stdout.write(`[STDOUT] ${msg.output}`)}, )
// Isolated context const ctx = await sandbox.codeInterpreter.createContext() try { await sandbox.codeInterpreter.runCode( `value = 'stored in ctx'`, { context: ctx }, ) await sandbox.codeInterpreter.runCode( `print(value)`, { context: ctx, onStdout: (msg) => process.stdout.write(`[STDOUT] ${msg.output}`) }, ) } finally { await sandbox.codeInterpreter.deleteContext(ctx) }}
main()See: code_interpreter (Python SDK) and codeInterpreter (TypeScript SDK)
Process Execution
Daytona SDK provides an option to execute shell commands and manage background processes in Sandboxes. The workDir for executing defaults to the current Sandbox working directory. Uses the WORKDIR specified in
the Dockerfile if present, or falling back to the user’s home directory if not - e.g. workspace/repo implies /my-work-dir/workspace/repo, but you can override it with an absolute path (by starting the path with /).
Running Commands
Daytona SDK provides an option to execute shell commands in Python and TypeScript. You can run commands with input, timeout, and environment variables.
# Execute any shell commandresponse = sandbox.process.exec("ls -la")print(response.result)
# Setting a working directory and a timeout
response = sandbox.process.exec("sleep 3", cwd="workspace/src", timeout=5)print(response.result)
# Passing environment variables
response = sandbox.process.exec("echo $CUSTOM_SECRET", env={ "CUSTOM_SECRET": "DAYTONA" })print(response.result)// Execute any shell commandconst response = await sandbox.process.executeCommand("ls -la");console.log(response.result);
// Setting a working directory and a timeoutconst response2 = await sandbox.process.executeCommand("sleep 3", "workspace/src", undefined, 5);console.log(response2.result);
// Passing environment variablesconst response3 = await sandbox.process.executeCommand("echo $CUSTOM_SECRET", ".", { "CUSTOM_SECRET": "DAYTONA" });console.log(response3.result);See: exec (Python SDK), executeCommand (TypeScript SDK)
Sessions (Background Processes)
Daytona SDK provides an option to start, stop, and manage background process sessions in Sandboxes. You can run long-running commands, monitor process status, and list all running processes.
Managing Long-Running Processes
Daytona SDK provides an option to start and stop background processes. You can run long-running commands and monitor process status.
# Check session's executed commandssession = sandbox.process.get_session(session_id)print(f"Session {process_id}:")for command in session.commands: print(f"Command: {command.command}, Exit Code: {command.exit_code}")
# List all running sessions
sessions = sandbox.process.list_sessions()for session in sessions: print(f"PID: {session.id}, Commands: {session.commands}")// Check session's executed commandsconst session = await sandbox.process.getSession(sessionId);console.log(`Session ${sessionId}:`);for (const command of session.commands) { console.log(`Command: ${command.command}, Exit Code: ${command.exitCode}`);}
// List all running sessionsconst sessions = await sandbox.process.listSessions();for (const session of sessions) { console.log(`PID: ${session.id}, Commands: ${session.commands}`);}See: get_session (Python SDK), list_sessions (Python SDK), getSession (TypeScript SDK), listSessions (TypeScript SDK)
Best Practices
Use the following best practices when working with process and code execution in Daytona SDK.
Resource Management
The following best practices apply to managing resources when executing processes:
- Use sessions for long-running operations
- Clean up sessions after execution
- Handle session exceptions properly
# Python - Clean up sessionsession_id = "long-running-cmd"try: sandbox.process.create_session(session_id) session = sandbox.process.get_session(session_id) # Do work...finally: sandbox.process.delete_session(session.session_id)// TypeScript - Clean up sessionconst sessionId = "long-running-cmd";try { await sandbox.process.createSession(sessionId); const session = await sandbox.process.getSession(sessionId); // Do work...} finally { await sandbox.process.deleteSession(session.sessionId);}See: create_session (Python SDK), delete_session (Python SDK), createSession (TypeScript SDK), deleteSession (TypeScript SDK)
Error Handling
The following best practices apply to error handling when executing processes:
- Handle process exceptions properly
- Log error details for debugging
- Use try-catch blocks for error handling
try: response = sandbox.process.code_run("invalid python code")except ProcessExecutionError as e: print(f"Execution failed: {e}") print(f"Exit code: {e.exit_code}") print(f"Error output: {e.stderr}")try { const response = await sandbox.process.codeRun("invalid typescript code");} catch (e) { if (e instanceof ProcessExecutionError) { console.error("Execution failed:", e); console.error("Exit code:", e.exitCode); console.error("Error output:", e.stderr); }}Common Issues
To troubleshoot common issues related to process and code execution, refer to the following table:
| Issue | Solutions |
|---|---|
Process Execution Failed | • Check command syntax • Verify required dependencies • Ensure sufficient permissions |
Process Timeout | • Adjust timeout settings • Optimize long-running operations • Consider using background processes |
Resource Limits | • Monitor process memory usage • Handle process cleanup properly • Use appropriate resource constraints |