AsyncCodeInterpreter | Daytona

AsyncCodeInterpreter

class AsyncCodeInterpreter()

Handles code interpretation and execution within a Sandbox. Currently supports only Python.

This class provides methods to execute code in isolated interpreter contexts, manage contexts, and stream execution output via callbacks. If subsequent code executions are performed in the same context, the variables, imports, and functions defined in the previous execution will be available.

For other languages, use the code_run method from the AsyncProcess interface, or execute the appropriate command directly in the sandbox terminal.

AsyncCodeInterpreter.init

def __init__(api_client: InterpreterApi)

Initialize a new AsyncCodeInterpreter instance.

Arguments:

AsyncCodeInterpreter.run_code

@intercept_errors(message_prefix="Failed to run code: ")
async def run_code(code: str,

*,

context: InterpreterContext | None = None,

on_stdout: OutputHandler[OutputMessage] | None = None,

on_stderr: OutputHandler[OutputMessage] | None = None,

on_error: OutputHandler[ExecutionError] | None = None,

envs: dict[str, str] | None = None,

timeout: int | None = None) -> ExecutionResult

Execute Python code in the sandbox.

By default, code runs in the default shared context which persists variables, imports, and functions across executions. To run in an isolated context, create a new context with create_context() and pass it as context argument.

Arguments:

Returns:

Raises:

Examples:

def handle_stdout(msg: OutputMessage):

print(f"STDOUT: {msg.output}", end="")

def handle_stderr(msg: OutputMessage):

print(f"STDERR: {msg.output}", end="")

def handle_error(err: ExecutionError):

print(f"ERROR: {err.name}: {err.value}")

code = '''

import sys

import time

for i in range(5):

print(i)

time.sleep(1)

sys.stderr.write("Counting done!")

'''

result = await sandbox.code_interpreter.run_code(

code=code,

on_stdout=handle_stdout,

on_stderr=handle_stderr,

on_error=handle_error,

timeout=10
)

AsyncCodeInterpreter.create_context

@intercept_errors(message_prefix="Failed to create interpreter context: ")
async def create_context(

cwd: str | None = None,

request_timeout: float | None = None) -> InterpreterContext

Create a new isolated interpreter context.

Contexts provide isolated execution environments with their own global namespace. Variables, imports, and functions defined in one context don’t affect others.

Arguments:

Returns:

Raises:

Examples:

# Create isolated context

ctx = await sandbox.code_interpreter.create_context()

# Execute code in this context

await sandbox.code_interpreter.run_code("x = 100", context=ctx)

# Variable only exists in this context

result = await sandbox.code_interpreter.run_code("print(x)", context=ctx)  # OK

# Won't see the variable in default context

result = await sandbox.code_interpreter.run_code("print(x)")  # NameError

# Clean up

await sandbox.code_interpreter.delete_context(ctx)

AsyncCodeInterpreter.list_contexts

@intercept_errors(message_prefix="Failed to list interpreter contexts: ")
async def list_contexts(

request_timeout: float | None = None) -> list[InterpreterContext]

List all user-created interpreter contexts.

The default context is not included in this list. Only contexts created via create_context() are returned.

Arguments:

Returns:

Raises:

Examples:

contexts = await sandbox.code_interpreter.list_contexts()

for ctx in contexts:

print(f"Context {ctx.id}: {ctx.language} at {ctx.cwd}")

AsyncCodeInterpreter.delete_context

@intercept_errors(message_prefix="Failed to delete interpreter context: ")
async def delete_context(context: InterpreterContext,

request_timeout: float | None = None) -> None

Delete an interpreter context and shut down all associated processes.

This permanently removes the context and all its state (variables, imports, etc.). The default context cannot be deleted.

Arguments:

Raises:

Examples:

ctx = await sandbox.code_interpreter.create_context()

# ... use context ...

await sandbox.code_interpreter.delete_context(ctx)

OutputMessage

class OutputMessage(BaseModel)

Represents stdout or stderr output from code execution.

Attributes:

ExecutionError

class ExecutionError(BaseModel)

Represents an error that occurred during code execution.

Attributes:

ExecutionResult

class ExecutionResult(BaseModel)

Result of code execution.

Attributes: