Code Execution
Run Python, TypeScript, and JavaScript code in your sandboxes through language kernels.
Daytona runs Python, TypeScript, and JavaScript code in sandboxes through language kernels, so untrusted or generated code executes in isolation from your application.
Every run is a code process that executes in a session with a language kernel. The kernel keeps state between runs in the same session, so variables, imports, and functions defined in one run are available in the next. Runs use a shared kernel per language by default; isolated runs and interpreter contexts give code its own kernel. To run shell commands and manage long-running processes, see process execution. To follow a run's output live, see log streaming.
Use cases
Code execution is used when an application runs Python, TypeScript, or JavaScript that it did not write or does not trust.
- AI-generated code: an agent writes code, runs it in the sandbox, and reads the output and errors to correct its next attempt. The code runs isolated from your application.
- Data analysis: the kernel keeps data, imports, and functions in memory between runs, so each step builds on the previous one, as in a notebook.
- Charts and tables: runs that plot or display data return charts and tables as artifacts with the result. Each artifact is keyed by MIME type, so an application renders it in the right format.
- Code interpreters for users: each user or conversation gets its own interpreter context, so state from one does not reach another. A context has its own kernel, working directory, and environment.
- Workers that share a context: contexts are addressed by ID. Any worker or process with the sandbox ID and the context ID runs code in the same context.
- Live output from long runs: the output of a run streams through log streaming while the code still runs. Exceptions arrive with their name, value, and traceback.
- One-off runs: an isolated kernel runs code with no state from earlier runs. The session is deleted after the run, so nothing the code defines reaches other runs.
Run code
Run code in a sandbox. Runs without a context share one kernel per language, so state from one run is available to later runs in that language. The default language is Python.
The result contains the standard output and standard error, rich outputs, the exception if the code raised one, and the exit status of the process.
from daytona import Daytona
daytona = Daytona()
sandbox = daytona.v2.create()
response = sandbox.run_code('''
def greet(name):
return f"Hello, {name}!"
print(greet("Daytona"))
''')
print(response.logs.stdout)| Parameter | Type | Description |
|---|---|---|
code | str | Sets the code to run. This parameter is required. |
language | str | Sets the language: python, typescript, or javascript. The default is python. |
context | InterpreterContext | Runs the code in an interpreter context instead of the shared kernel. |
isolated | bool | Runs the code in a temporary kernel. The default is False. |
cwd | str | Sets the working directory for the run. |
env | Mapping[str, str] | Sets environment variables for the shared kernel. The variables apply when the kernel is first created. |
timeout | float | Sets how many seconds the client waits. 0 means no limit. On timeout, the kernel is interrupted and the interrupted result is returned. |
The response has the following fields:
| Field | Description |
|---|---|
logs | Holds the standard output and standard error. |
results | Holds the rich outputs. |
error | Holds the exception, if the code raised one. |
process | Holds the exit status of the process. |
Artifacts
Rich outputs such as charts and tables are returned with the result, keyed by MIME type.
from daytona import Daytona
daytona = Daytona()
sandbox = daytona.v2.create()
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.run_code(code)
for result in response.results:
print(list(result.data)) # MIME types, for example ['image/png', 'text/plain']The response has the following fields:
| Field | Description |
|---|---|
results | Holds the rich outputs. |
text, html, png, svg, json | Each of these fields of a result mirrors the matching MIME type in data. |
is_main_result | Is True for the value of the last expression and False for displayed outputs. |
Run code in an isolated kernel
Run code in a temporary kernel that starts with no state. Daytona creates a session with a new kernel, runs the code, and deletes the session after the run. Nothing the code defines is visible to other runs, and the code does not see state from the shared kernel or from interpreter contexts.
from daytona import Daytona
daytona = Daytona()
sandbox = daytona.v2.create()
sandbox.run_code("value = 42")
# The isolated kernel does not see variables from the shared kernel
response = sandbox.run_code("print(value)", isolated=True)
if response.error:
print(response.error.name) # NameError| Parameter | Type | Description |
|---|---|---|
isolated | bool | Runs the code in a temporary kernel when set to True. The default is False. |
cwd | str | Sets the working directory of the temporary kernel. |
env | Mapping[str, str] | Sets environment variables of the temporary kernel. |
Interpreter contexts
An interpreter context is a session with its own language kernel, working directory, and environment. State persists across runs in a context and is not shared with the shared kernel or other contexts. A context lives until deleted, so its kernel uses memory while idle.
In the Toolbox API, a context is a session whose kernel is a language. Sessions with a shell kernel run shell commands; see sessions.
Create a context
Create an interpreter context and run code in it. Run code with the context handle, or pass the handle to a run in the sandbox.
from daytona import Daytona
daytona = Daytona()
sandbox = daytona.v2.create()
ctx = sandbox.interpreter.create_context(language="python", env={"STAGE": "dev"})
try:
ctx.run("value = 'stored in ctx'")
result = sandbox.run_code("print(value)", context=ctx)
print(result.logs.stdout)
finally:
ctx.close()| Parameter | Type | Description |
|---|---|---|
language | str | Sets the language: python, typescript, or javascript. This parameter is required. |
context_id | str | Sets the context ID for reconnecting later. If omitted, an ID is generated. |
cwd | str | Sets the working directory of the kernel. |
env | Mapping[str, str] | Sets the kernel environment variables. Runs in a context do not accept env. |
List contexts
List a sandbox's interpreter contexts. The API also lists shell sessions; the SDKs do not.
from daytona import Daytona
daytona = Daytona()
sandbox = daytona.v2.create()
for ctx in sandbox.interpreter.list_contexts():
print(f"Context: {ctx.context_id}, Language: {ctx.language}")Reconnect to a context
Reconnect to an existing context from another worker or process. Contexts are addressed by ID, so any client with the sandbox ID and the context ID can run code in the context.
from daytona import Daytona
daytona = Daytona()
sandbox = daytona.v2.create()
# Worker A: create a context with a known ID
ctx = sandbox.interpreter.create_context(language="python", context_id="my-context")
ctx.run("x = 42")
# Worker B: reconnect to the context by ID
context = sandbox.interpreter.connect_context("my-context", language="python")
response = context.run("print(x)")| Parameter | Type | Description |
|---|---|---|
language | str | Sets the context language. This parameter is required when you pass an ID. Without language, connect_context() raises DaytonaError with code BAD_REQUEST. |
Delete a context
Delete an interpreter context. Deleting a context shuts its kernel down and frees its memory.
from daytona import Daytona
daytona = Daytona()
sandbox = daytona.v2.create()
ctx = sandbox.interpreter.create_context(language="python")
try:
ctx.run("data = list(range(10_000_000))")
finally:
sandbox.interpreter.delete_context(ctx)