Skip to main content

Python API Reference

Sandbox

Synchronous sandbox client. Use as a context manager or manage the lifecycle manually.

Sandbox.create()

Create a new sandbox.

@classmethod
def create(
cls,
flavor: str = "python-3.12",
*,
memory: int = 512,
cpu: int = 1,
ttl: int = 60,
metadata: dict[str, str] | None = None,
api_key: str | None = None,
base_url: str | None = None,
timeout: float | None = None,
max_retries: int | None = None,
) -> "Sandbox"

Parameters

ParameterDefaultDescription
flavor'python-3.12'Environment preset
memory512Memory in MB (max 8192)
cpu1vCPU count (max 4)
ttl60Lifetime in minutes (max 480)
metadataNoneArbitrary key-value tags
api_keyNoneFalls back to CODECAPSULES_API_KEY env var
timeoutNoneHTTP timeout in seconds (default 30)
max_retriesNoneRetries on transient errors (default 2)
sb = Sandbox.create("python-3.12", memory=2048, ttl=120)

Sandbox.get()

Fetch an existing sandbox by ID.

@classmethod
def get(
cls,
sandbox_id: str,
*,
api_key: str | None = None,
base_url: str | None = None,
timeout: float | None = None,
) -> "Sandbox"
sb = Sandbox.get("sb_01hx...")
print(sb.status) # 'running'

Properties

PropertyTypeDescription
idstrUnique sandbox ID (e.g. sb_01hx...)
flavorstrEnvironment flavor (e.g. python-3.12)
statusSandboxStatusLast known status (call refresh() for a live value)
expires_atdatetimeWhen the sandbox will be automatically deleted
infoSandboxInfoFull sandbox info snapshot

Methods

sb.exec()

Execute a shell command and wait for it to complete.

def exec(
self,
command: str,
*,
stdin: str | None = None,
timeout: int = 30,
env: dict[str, str] | None = None,
) -> ExecResult

Parameters

ParameterDefaultDescription
commandShell command to run
stdinNoneContent written to stdin
timeout30Timeout in seconds (max 300)
envNoneAdditional environment variables

ExecResult

AttributeTypeDescription
stdoutstrStandard output
stderrstrStandard error
exit_codeintExit code (0 = success)
duration_msfloatWall-clock time in milliseconds
exec_idstrUnique execution ID
commandstrThe command that was run
started_atdatetimeExecution start time
completed_atdatetimeExecution end time
result = sb.exec("python --version")
print(result.stdout) # "Python 3.12.3\n"
print(result.exit_code) # 0

# With options
sb.exec("pip install numpy", timeout=120)
sb.exec("echo $FOO", env={"FOO": "bar"})

sb.exec_stream()

Execute a command and stream output as it arrives.

def exec_stream(
self,
command: str,
*,
timeout: int = 300,
env: dict[str, str] | None = None,
) -> Iterator[str]

Yields chunks of stdout and stderr as they are produced.

for chunk in sb.exec_stream("python train.py"):
print(chunk, end="", flush=True)

sb.upload()

Upload content to a path inside the sandbox.

def upload(self, sandbox_path: str, content: bytes | str) -> FileInfo

FileInfo

AttributeTypeDescription
pathstrPath inside the sandbox
size_bytesintFile size in bytes
created_atdatetimeUpload time
sb.upload("/workspace/script.py", open("script.py", "rb").read())
sb.upload("/workspace/config.json", '{"key": "value"}')

sb.download()

Download a file from the sandbox as bytes.

def download(self, sandbox_path: str) -> bytes
raw = sb.download("/workspace/output.json")
result = json.loads(raw)

sb.logs()

Fetch sandbox logs.

def logs(
self,
*,
since: datetime | None = None,
limit: int = 100,
) -> list[LogEntry]

LogEntry

AttributeTypeDescription
tsdatetimeTimestamp
sourcestr'system' or 'exec'
messagestrLog message
exec_idstr | NoneAssociated exec ID
entries = sb.logs(limit=50)
for e in entries:
print(f"[{e.source}] {e.message}")

sb.metrics()

Get live resource usage for the sandbox.

def metrics(self) -> SandboxMetrics

SandboxMetrics

AttributeTypeDescription
cpu_percentfloatCPU usage percentage
memory_used_mbfloatMemory used in MB
memory_limit_mbfloatMemory limit in MB
disk_used_mbfloatDisk used in MB
disk_limit_mbfloatDisk limit in MB
exec_countintNumber of exec calls
uptime_secondsfloatSandbox uptime
m = sb.metrics()
print(f"CPU: {m.cpu_percent}%, RAM: {m.memory_used_mb}/{m.memory_limit_mb}MB")

sb.refresh()

Re-fetch sandbox info and update cached properties.

def refresh(self) -> "Sandbox"

sb.wait_until_running()

Poll until status == 'running', then return. Rarely needed; create() already waits.

def wait_until_running(
self,
*,
timeout: float = 30.0,
interval: float = 0.25,
) -> "Sandbox"

sb.stop()

Gracefully stop the sandbox. Transitions to 'stopped'.

def stop(self) -> None

sb.delete()

Delete the sandbox and release all resources immediately.

def delete(self) -> None

AsyncSandbox

Async variant of Sandbox. All methods are coroutines. Use with async with or await.

from codecapsules_sandbox import AsyncSandbox

Factory

@classmethod
async def create(
cls,
flavor: str = "python-3.12",
*,
memory: int = 512,
cpu: int = 1,
ttl: int = 60,
metadata: dict[str, str] | None = None,
api_key: str | None = None,
...
) -> "AsyncSandbox"

Async context manager

async with AsyncSandbox.create(flavor="python-3.12") as sb:
result = await sb.exec("python --version")
print(result.stdout)

Methods

AsyncSandbox has the same methods as Sandbox, but all are async:

Sync (Sandbox)Async (AsyncSandbox)
sb.exec()await sb.exec()
sb.exec_stream()async for chunk in sb.exec_stream()
sb.upload()await sb.upload()
sb.download()await sb.download()
sb.logs()await sb.logs()
sb.metrics()await sb.metrics()
sb.refresh()await sb.refresh()
sb.delete()await sb.delete()
async with AsyncSandbox.create() as sb:
# Stream output asynchronously
async for chunk in sb.exec_stream("python train.py"):
print(chunk, end="", flush=True)

Exceptions

All exceptions extend SandboxError.

ExceptionWhen raised
SandboxAuthErrorInvalid or missing API key
SandboxNotFoundErrorSandbox ID not found
SandboxNotReadyErrorSandbox in error state or timed out waiting to start
SandboxExecTimeoutErrorexec() exceeded the timeout
SandboxRateLimitErrorToo many requests
SandboxQuotaErrorAccount quota exceeded
SandboxAPIErrorUnexpected API error (includes HTTP status and response body)
from codecapsules_sandbox import Sandbox, SandboxExecTimeoutError

try:
with Sandbox.create() as sb:
sb.exec("sleep 999", timeout=5)
except SandboxExecTimeoutError:
print("Command timed out")