Skip to content

Process and Code Execution

View as Markdown

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.

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.

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

For more information, see the Python SDK, TypeScript SDK, Ruby SDK, Go SDK, and API references:

code_run (Python SDK)

codeRun (TypeScript SDK)

code_run (Ruby SDK)

ExecuteCommand (Go SDK)

execute command (API)

Run code (stateful)

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.

from daytona import Daytona, OutputMessage
def handle_stdout(message: OutputMessage):
print(f"[STDOUT] {message.output}")
daytona = Daytona()
sandbox = daytona.create()
# Shared default context
result = sandbox.code_interpreter.run_code(
"counter = 1\nprint(f'Counter initialized at {counter}')",
on_stdout=handle_stdout,
)
# Isolated context
ctx = 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)

For more information, see the Python SDK, TypeScript SDK, Ruby SDK, Go SDK, and API references:

run_code (Python SDK)

create_context (Python SDK)

delete_context (Python SDK)

runCode (TypeScript SDK)

createContext (TypeScript SDK)

deleteContext (TypeScript SDK)

code_run (Ruby SDK)

RunCode (Go SDK)

CreateContext (Go SDK)

DeleteContext (Go SDK)

code interpreter (API)

Command execution

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.

# Execute any shell command
response = 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)

For more information, see the Python SDK, TypeScript SDK, Ruby SDK, Go SDK, CLI, and API references:

exec (Python SDK)

executeCommand (TypeScript SDK)

exec (Ruby SDK)

ExecuteCommand (Go SDK)

daytona exec (CLI)

execute command (API)

Session operations

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.

# Check session's executed commands
session = 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 sessions
sessions = sandbox.process.list_sessions()
for session in sessions:
print(f"Session: {session.session_id}, Commands: {session.commands}")

For more information, see the Python SDK, TypeScript SDK, Ruby SDK, Go SDK, and API references:

get_session (Python SDK)

list_sessions (Python SDK)

getSession (TypeScript SDK)

listSessions (TypeScript SDK)

get_session (Ruby SDK)

list_sessions (Ruby SDK)

GetSession (Go SDK)

ListSessions (Go SDK)

get session (API)

list sessions (API)

Execute interactive commands

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.

session_id = "interactive-session"
sandbox.process.create_session(session_id)
# Execute command that requires confirmation
command = sandbox.process.execute_session_command(
session_id,
SessionExecuteRequest(
command='pip uninstall requests',
run_async=True,
),
)
# Stream logs asynchronously
logs_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 command
sandbox.process.send_session_command_input(session_id, command.cmd_id, "y")
# Wait for logs to complete
await logs_task

For more information, see the Python SDK, TypeScript SDK, Ruby SDK, Go SDK, and API references:

create_session (Python SDK)

execute_session_command (Python SDK)

send_session_command_input (Python SDK)

get_session_command_logs_async (Python SDK)

createSession (TypeScript SDK)

executeSessionCommand (TypeScript SDK)

sendSessionCommandInput (TypeScript SDK)

getSessionCommandLogs (TypeScript SDK)

create_session (Ruby SDK)

execute_session_command (Ruby SDK)

send_session_command_input (Ruby SDK)

CreateSession (Go SDK)

ExecuteSessionCommand (Go SDK)

GetSessionCommandLogsStream (Go SDK)

create session (API)

execute session command (API)

Resource management

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 - Clean up session
session_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)

For more information, see the Python SDK, TypeScript SDK, Ruby SDK, Go SDK, and API references:

create_session (Python SDK)

delete_session (Python SDK)

createSession (TypeScript SDK)

deleteSession (TypeScript SDK)

create_session (Ruby SDK)

delete_session (Ruby SDK)

CreateSession (Go SDK)

DeleteSession (Go SDK)

create session (API)

delete session (API)

Error handling

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.

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

For more information, see the Python SDK, TypeScript SDK, Ruby SDK, and Go SDK references.

Common issues

Daytona provides solutions for troubleshooting common issues related to process and code execution.

IssueSolutions
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