Daytona provides process and code execution capabilities through the process module in sandboxes.
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.
Stateless execution inherits the sandbox language that you choose at sandbox creation time. The stateful interpreter supports only Python.
Run code (stateless)
Daytona provides methods to run code snippets in sandboxes using stateless execution. Each invocation starts from a clean interpreter, making it ideal for independent code snippets.
Python
TypeScript
Ruby
Go
API
Copy
# Run Python coderesponse = sandbox.process.code_run('''def greet(name): return f"Hello, {name}!"print(greet("Daytona"))''')print(response.result)
Copy
// 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 timeout (5 seconds)response = await sandbox.process.codeRun( 'setTimeout(() => console.log("Done"), 2000);', undefined, 5);console.log(response.result);
Daytona provides methods to run code with persistent state using the code interpreter. You can maintain variables and imports between calls, create isolated contexts, and control environment variables.
Daytona provides methods to execute shell commands in sandboxes. You can run commands with working directory, timeout, and environment variable options.
The working directory defaults to the sandbox working directory. It uses the WORKDIR specified in the Dockerfile if present, or falls back to the user’s home directory if not (e.g., workspace/repo implies /home/daytona/workspace/repo). You can override it with an absolute path by starting the path with /.
Execute commands
Daytona provides methods to execute shell commands in sandboxes by providing the command string and optional parameters for working directory, timeout, and environment variables. You can also use the daytona exec CLI command for quick command execution.
Python
TypeScript
Ruby
Go
CLI
API
Copy
# Execute any shell commandresponse = sandbox.process.exec("ls -la")print(response.result)# Setting a working directory and a timeoutresponse = sandbox.process.exec("sleep 3", cwd="workspace/src", timeout=5)print(response.result)# Passing environment variablesresponse = sandbox.process.exec("echo $CUSTOM_SECRET", env={ "CUSTOM_SECRET": "DAYTONA" })print(response.result)
Copy
// 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);
Copy
# Execute any shell commandresponse = sandbox.process.exec(command: 'ls -la')puts response.result# Setting a working directory and a timeoutresponse = sandbox.process.exec(command: 'sleep 3', cwd: 'workspace/src', timeout: 5)puts response.result# Passing environment variablesresponse = sandbox.process.exec( command: 'echo $CUSTOM_SECRET', env: { 'CUSTOM_SECRET' => 'DAYTONA' })puts response.result
Copy
// Execute any shell commandresponse, err := sandbox.Process.ExecuteCommand(ctx, "ls -la")if err != nil { log.Fatal(err)}fmt.Println(response.Result)// Setting a working directory and a timeoutresponse, err = sandbox.Process.ExecuteCommand(ctx, "sleep 3", options.WithCwd("workspace/src"), options.WithExecuteTimeout(5*time.Second),)if err != nil { log.Fatal(err)}fmt.Println(response.Result)// Passing environment variablesresponse, err = sandbox.Process.ExecuteCommand(ctx, "echo $CUSTOM_SECRET", options.WithCommandEnv(map[string]string{"CUSTOM_SECRET": "DAYTONA"}),)if err != nil { log.Fatal(err)}fmt.Println(response.Result)
Copy
# Execute any shell commanddaytona exec my-sandbox -- ls -la# Setting a working directory and a timeoutdaytona exec my-sandbox --cwd workspace/src --timeout 5 -- sleep 3# Passing environment variables (use shell syntax)daytona exec my-sandbox -- sh -c 'CUSTOM_SECRET=DAYTONA echo $CUSTOM_SECRET'
Daytona provides methods to manage background process sessions in sandboxes. You can create sessions, execute commands, monitor status, and manage long-running processes.
Get session status
Daytona provides methods to get session status and list all sessions in a sandbox by providing the session ID.
Python
TypeScript
Ruby
Go
API
Copy
# Check session's executed commandssession = sandbox.process.get_session(session_id)print(f"Session {session_id}:")for command in session.commands: print(f"Command: {command.command}, Exit Code: {command.exit_code}")# List all running sessionssessions = sandbox.process.list_sessions()for session in sessions: print(f"Session: {session.session_id}, Commands: {session.commands}")
Copy
// 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(`Session: ${session.sessionId}, Commands: ${session.commands}`);}
Copy
# Check session's executed commandssession = sandbox.process.get_session(session_id)puts "Session #{session_id}:"session.commands.each do |command| puts "Command: #{command.command}, Exit Code: #{command.exit_code}"end# List all running sessionssessions = sandbox.process.list_sessionssessions.each do |session| puts "Session: #{session.session_id}, Commands: #{session.commands}"end
# Get session infocurl 'https://proxy.app.daytona.io/toolbox/{sandboxId}/process/session/{sessionId}'# List all sessionscurl 'https://proxy.app.daytona.io/toolbox/{sandboxId}/process/session'
Daytona provides methods to execute interactive commands in sessions. You can send input to running commands that expect user interaction, such as confirmations or interactive tools like database CLIs and package managers.
Python
TypeScript
Ruby
Go
API
Copy
session_id = "interactive-session"sandbox.process.create_session(session_id)# Execute command that requires confirmationcommand = sandbox.process.execute_session_command( session_id, SessionExecuteRequest( command='pip uninstall requests', run_async=True, ),)# Stream logs asynchronouslylogs_task = asyncio.create_task( sandbox.process.get_session_command_logs_async( session_id, command.cmd_id, lambda log: print(f"[STDOUT]: {log}"), lambda log: print(f"[STDERR]: {log}"), ))await asyncio.sleep(1)# Send input to the commandsandbox.process.send_session_command_input(session_id, command.cmd_id, "y")# Wait for logs to completeawait logs_task
Copy
const sessionId = 'interactive-session'await sandbox.process.createSession(sessionId)// Execute command that requires confirmationconst command = await sandbox.process.executeSessionCommand(sessionId, { command: 'pip uninstall requests', runAsync: true,})// Stream logs asynchronouslyconst logPromise = sandbox.process.getSessionCommandLogs( sessionId, command.cmdId!, (stdout) => console.log('[STDOUT]:', stdout), (stderr) => console.log('[STDERR]:', stderr),)await new Promise((resolve) => setTimeout(resolve, 1000))// Send input to the commandawait sandbox.process.sendSessionCommandInput(sessionId, command.cmdId!, 'y')// Wait for logs to completeawait logPromise
Copy
session_id = "interactive-session"sandbox.process.create_session(session_id)# Execute command that requires confirmationinteractive_command = sandbox.process.execute_session_command( session_id: session_id, req: Daytona::SessionExecuteRequest.new( command: 'pip uninstall requests', run_async: true ))# Wait a moment for the command to startsleep 1# Send input to the commandsandbox.process.send_session_command_input( session_id: session_id, command_id: interactive_command.cmd_id, data: "y")# Get logs for the interactive command asynchronouslysandbox.process.get_session_command_logs_async( session_id: session_id, command_id: interactive_command.cmd_id, on_stdout: ->(log) { puts "[STDOUT]: #{log}" }, on_stderr: ->(log) { puts "[STDERR]: #{log}" })
Copy
sessionID := "interactive-session"err := sandbox.Process.CreateSession(ctx, sessionID)if err != nil { log.Fatal(err)}// Execute command that requires confirmationresult, err := sandbox.Process.ExecuteSessionCommand(ctx, sessionID, "pip uninstall requests", true)if err != nil { log.Fatal(err)}cmdID := result["cmdId"].(string)// Stream logs asynchronouslystdout := make(chan string)stderr := make(chan string)go func() { err := sandbox.Process.GetSessionCommandLogsStream(ctx, sessionID, cmdID, stdout, stderr) if err != nil { log.Println("Log stream error:", err) }}()time.Sleep(1 * time.Second)// Note: SendSessionCommandInput is not available in Go SDK// Use the API endpoint directly for sending input// Read logsfor msg := range stdout { fmt.Printf("[STDOUT]: %s\n", msg)}
Daytona provides methods to manage session resources. You should use sessions for long-running operations, clean up sessions after execution, and handle exceptions properly.
Python
TypeScript
Ruby
Go
API
Copy
# 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)
Daytona provides methods to handle errors when executing processes. You should handle process exceptions properly, log error details for debugging, and use try-catch blocks for error handling.
Python
TypeScript
Ruby
Go
API
Copy
from daytona import DaytonaErrortry: 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}")
Copy
import { DaytonaError } from '@daytonaio/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); }}
Copy
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}" endrescue StandardError => e puts "Execution failed: #{e}"end