Skip to main content
The OpenSandbox Python SDK provides secure, isolated execution environments with comprehensive file system access, command execution, and resource management capabilities.

Installation

pip install opensandbox

Core Classes

Sandbox

Main entrypoint for creating and managing sandbox instances.

Class Methods

create()
Create a new sandbox instance with the specified configuration.
from opensandbox import Sandbox
from opensandbox.models.sandboxes import SandboxImageSpec, SandboxImageAuth
from datetime import timedelta

sandbox = await Sandbox.create(
    "python:3.11",
    timeout=timedelta(minutes=30),
    env={"PYTHONPATH": "/workspace"},
    resource={"cpu": "2", "memory": "4Gi"},
)
image
SandboxImageSpec | str
required
Container image specification. Can be a string (e.g., "python:3.11") or a SandboxImageSpec object with authentication.
timeout
timedelta
default:"timedelta(minutes=10)"
Maximum sandbox lifetime before automatic termination.
ready_timeout
timedelta
default:"timedelta(seconds=30)"
Maximum time to wait for sandbox to become ready.
env
dict[str, str] | None
Environment variables for the sandbox.
metadata
dict[str, str] | None
Custom metadata tags for the sandbox.
resource
dict[str, str] | None
default:"{\"cpu\": \"1\", \"memory\": \"2Gi\"}"
Resource limits (CPU, memory, etc.).
network_policy
NetworkPolicy | None
Optional outbound network policy (egress).
extensions
dict[str, str] | None
Opaque extension parameters passed through to the server.
entrypoint
list[str] | None
default:"[\"tail\", \"-f\", \"/dev/null\"]"
Command to run as entrypoint.
volumes
list[Volume] | None
Optional list of volume mounts for persistent storage.
connection_config
ConnectionConfig | None
Connection configuration for API server.
health_check
Callable[[Sandbox], Awaitable[bool]] | None
Custom async health check function.
health_check_polling_interval
timedelta
default:"timedelta(milliseconds=200)"
Time between health check attempts.
skip_health_check
bool
default:"False"
If True, do not wait for sandbox readiness/health.
return
Sandbox
Fully configured and ready Sandbox instance.
connect()
Connect to an existing sandbox instance by ID.
sandbox = await Sandbox.connect(
    sandbox_id="existing-sandbox-id",
    connection_config=config
)
sandbox_id
str
required
ID of the existing sandbox.
connection_config
ConnectionConfig | None
Connection configuration.
health_check
Callable[[Sandbox], Awaitable[bool]] | None
Custom async health check function.
connect_timeout
timedelta
default:"timedelta(seconds=30)"
Maximum time to wait for sandbox readiness/health after connecting.
health_check_polling_interval
timedelta
default:"timedelta(milliseconds=200)"
Polling interval while waiting for readiness/health.
skip_health_check
bool
default:"False"
If True, do not wait for readiness/health.
return
Sandbox
Connected Sandbox instance.
resume()
Resume a paused sandbox by ID and return a new Sandbox instance.
sandbox = await Sandbox.resume(
    sandbox_id="paused-sandbox-id",
    connection_config=config
)
sandbox_id
str
required
ID of the paused sandbox to resume.
connection_config
ConnectionConfig | None
Connection configuration.
health_check
Callable[[Sandbox], Awaitable[bool]] | None
Optional custom async health check function.
resume_timeout
timedelta
default:"timedelta(seconds=30)"
Maximum time to wait for sandbox readiness/health after resuming.
health_check_polling_interval
timedelta
default:"timedelta(milliseconds=200)"
Polling interval while waiting for readiness/health.
skip_health_check
bool
default:"False"
If True, do not wait for readiness/health.
return
Sandbox
Resumed Sandbox instance.

Instance Methods

get_info()
Get the current status of the sandbox.
info = await sandbox.get_info()
print(f"State: {info.status.state}")
return
SandboxInfo
Current sandbox status including state and metadata.
get_endpoint()
Get a specific network endpoint for the sandbox.
endpoint = await sandbox.get_endpoint(80)
print(f"Endpoint: {endpoint.endpoint}")
port
int
required
The port number to get the endpoint for.
return
SandboxEndpoint
Endpoint information including connection details.
get_metrics()
Get the current resource usage metrics for the sandbox.
metrics = await sandbox.get_metrics()
print(f"Memory: {metrics.memory_used_in_mib}MB")
return
SandboxMetrics
Current sandbox metrics including CPU, memory, and I/O statistics.
renew()
Renew the sandbox expiration time to delay automatic termination.
await sandbox.renew(timedelta(minutes=30))
timeout
timedelta
required
Duration to add to the current time to set the new expiration.
return
SandboxRenewResponse
Renew response including the new expiration time.
pause()
Pause the sandbox while preserving its state.
await sandbox.pause()
kill()
Send a termination signal to the remote sandbox instance.
await sandbox.kill()
close()
Close local resources associated with the sandbox.
await sandbox.close()
is_healthy()
Check if the sandbox is healthy and responsive.
healthy = await sandbox.is_healthy()
return
bool
True if sandbox is healthy, False otherwise.

Properties

files
Provides access to file system operations within the sandbox.
await sandbox.files.write_file("hello.txt", "Hello World")
content = await sandbox.files.read_file("hello.txt")
type
Filesystem
File system operations interface.
commands
Provides access to command execution operations.
result = await sandbox.commands.run("python script.py")
print(result.logs.stdout[0].text)
type
Commands
Command execution interface.
metrics
Provides access to sandbox metrics and monitoring.
metrics = await sandbox.metrics.get_metrics(sandbox.id)
type
Metrics
Metrics and monitoring interface.

SandboxManager

Administrative interface for managing multiple sandbox instances.

Class Methods

create()
Create a SandboxManager instance.
from opensandbox import SandboxManager

manager = await SandboxManager.create(connection_config=config)
connection_config
ConnectionConfig | None
Connection configuration for the manager.
return
SandboxManager
Configured sandbox manager instance.

Instance Methods

list_sandbox_infos()
List sandboxes with filtering options.
from opensandbox.models.sandboxes import SandboxFilter

sandboxes = await manager.list_sandbox_infos(
    SandboxFilter(states=["RUNNING"], page_size=10)
)
filter
SandboxFilter
required
Filter criteria for sandbox listing.
return
PagedSandboxInfos
Paged sandbox information matching the filter criteria.
get_sandbox_info()
Get information for a single sandbox by ID.
info = await manager.get_sandbox_info("sandbox-id")
sandbox_id
str
required
Sandbox ID to retrieve information for.
return
SandboxInfo
SandboxInfo for the specified sandbox.
kill_sandbox()
Terminate a single sandbox.
await manager.kill_sandbox("sandbox-id")
sandbox_id
str
required
Sandbox ID to terminate.
renew_sandbox()
Renew expiration time for a single sandbox.
await manager.renew_sandbox("sandbox-id", timedelta(minutes=30))
sandbox_id
str
required
Sandbox ID to renew.
timeout
timedelta
required
Duration to add to the current time to set the new expiration.
return
SandboxRenewResponse
Renew response including the new expiration time.
pause_sandbox()
Pause a single sandbox while preserving its state.
await manager.pause_sandbox("sandbox-id")
sandbox_id
str
required
Sandbox ID to pause.
resume_sandbox()
Resume a previously paused sandbox.
await manager.resume_sandbox("sandbox-id")
sandbox_id
str
required
Sandbox ID to resume.
close()
Close local resources associated with the sandbox manager.
await manager.close()

Service Interfaces

Commands

Command execution service for sandbox environments.

run()

Execute a shell command in the sandbox environment.
from opensandbox.models.execd import RunCommandOpts, ExecutionHandlers

# Simple execution
result = await sandbox.commands.run("echo 'Hello World'")
print(result.logs.stdout[0].text)

# With handlers
handlers = ExecutionHandlers(
    on_stdout=lambda msg: print(f"STDOUT: {msg.text}"),
    on_stderr=lambda msg: print(f"STDERR: {msg.text}"),
)
result = await sandbox.commands.run(
    "python script.py",
    opts=RunCommandOpts(background=False),
    handlers=handlers
)
command
str
required
Shell command text to execute.
opts
RunCommandOpts | None
Command execution options (e.g., background, working_directory).
handlers
ExecutionHandlers | None
Optional async handlers for streaming events (stdout/stderr/result/init/complete/error).
return
Execution
An Execution handle representing the running command instance.

interrupt()

Interrupt and terminate a running command execution.
await sandbox.commands.interrupt("execution-id")
execution_id
str
required
Unique identifier of the execution to interrupt.

get_command_status()

Get the current running status for a command.
status = await sandbox.commands.get_command_status("execution-id")
execution_id
str
required
Unique identifier of the execution to query.
return
CommandStatus
CommandStatus describing running state and exit code if available.

get_background_command_logs()

Get background command logs (non-streamed).
logs = await sandbox.commands.get_background_command_logs("execution-id", cursor=0)
execution_id
str
required
Unique identifier of the execution to query.
cursor
int | None
Optional line cursor for incremental reads.
return
CommandLogs
CommandLogs containing raw output and latest cursor.

Filesystem

Filesystem operations service for sandbox environments.

read_file()

Read the content of a file as a string.
content = await sandbox.files.read_file("/tmp/hello.txt")
print(content)
path
str
required
The absolute or relative path to the file to read.
encoding
str
default:"utf-8"
Character encoding for the file content.
range_header
str | None
HTTP byte range to read (e.g., “bytes=0-1023”).
return
str
The file content as a string.

read_bytes()

Read the content of a file as bytes.
content = await sandbox.files.read_bytes("/tmp/image.png")
path
str
required
The absolute or relative path to the file to read.
range_header
str | None
HTTP byte range to read (e.g., “bytes=0-1023”).
return
bytes
The file content as bytes.

read_bytes_stream()

Stream file content as bytes chunks.
async for chunk in sandbox.files.read_bytes_stream("/tmp/large-file.bin"):
    process(chunk)
path
str
required
The absolute or relative path to the file to read.
chunk_size
int
default:"65536"
Size of each chunk in bytes.
range_header
str | None
HTTP byte range to read (e.g., “bytes=0-1023”).
return
AsyncIterator[bytes]
Async iterator yielding bytes chunks.

write_files()

Write content to files based on the provided write entries.
from opensandbox.models.filesystem import WriteEntry

await sandbox.files.write_files([
    WriteEntry(path="/tmp/hello.txt", data="Hello World", mode=644)
])
entries
list[WriteEntry]
required
List of WriteEntry objects specifying files to write and their content.

write_file()

Write content to a single file (convenience method).
await sandbox.files.write_file("/tmp/hello.txt", "Hello World")
path
str
required
Destination file path.
data
str | bytes | IOBase
required
Content to write.
encoding
str
default:"utf-8"
Character encoding.
mode
int
default:"755"
Unix file permissions.
owner
str | None
Owner username.
group
str | None
Group name.

create_directories()

Create directories based on the provided entries.
from opensandbox.models.filesystem import WriteEntry

await sandbox.files.create_directories([
    WriteEntry(path="/tmp/mydir", mode=755)
])
entries
list[WriteEntry]
required
List of WriteEntry objects specifying directories to create.

delete_files()

Delete the specified files.
await sandbox.files.delete_files(["/tmp/hello.txt"])
paths
list[str]
required
List of file paths to delete.

delete_directories()

Delete the specified directories.
await sandbox.files.delete_directories(["/tmp/mydir"])
paths
list[str]
required
List of directory paths to delete.

move_files()

Move files from source to destination paths.
from opensandbox.models.filesystem import MoveEntry

await sandbox.files.move_files([
    MoveEntry(source="/tmp/old.txt", destination="/tmp/new.txt")
])
entries
list[MoveEntry]
required
List of MoveEntry objects specifying source and destination paths.

set_permissions()

Set file system permissions for the specified entries.
from opensandbox.models.filesystem import SetPermissionEntry

await sandbox.files.set_permissions([
    SetPermissionEntry(path="/tmp/script.sh", mode=755)
])
entries
list[SetPermissionEntry]
required
List of SetPermissionEntry objects specifying files and their new permissions.

replace_contents()

Replace content in files based on search and replace patterns.
from opensandbox.models.filesystem import ContentReplaceEntry

await sandbox.files.replace_contents([
    ContentReplaceEntry(
        path="/tmp/config.txt",
        search="old_value",
        replace="new_value"
    )
])
entries
list[ContentReplaceEntry]
required
List of ContentReplaceEntry objects specifying replacement operations.
Search for files and directories based on the specified criteria.
from opensandbox.models.filesystem import SearchEntry

files = await sandbox.files.search(
    SearchEntry(path="/tmp", pattern="*.txt")
)
for f in files:
    print(f.path)
entry
SearchEntry
required
SearchEntry object containing search parameters and criteria.
return
list[EntryInfo]
List of EntryInfo objects containing metadata for matching files/directories.

get_file_info()

Retrieve file information for the specified paths.
info_map = await sandbox.files.get_file_info(["/tmp/hello.txt"])
for path, info in info_map.items():
    print(f"{path}: {info.size} bytes")
paths
list[str]
required
List of file/directory paths to get information for.
return
dict[str, EntryInfo]
Map where keys are file paths and values are EntryInfo objects.

Configuration

ConnectionConfig

Connection configuration for API server communication.
from opensandbox.config import ConnectionConfig
from datetime import timedelta

config = ConnectionConfig(
    api_key="your-api-key",
    domain="api.opensandbox.io",
    request_timeout=timedelta(seconds=60)
)
api_key
str
API Key for authentication (can also be set via OPEN_SANDBOX_API_KEY environment variable).
domain
str
The endpoint domain of the sandbox service (can also be set via OPEN_SANDBOX_DOMAIN environment variable).
protocol
str
default:"http"
HTTP protocol (http/https).
request_timeout
timedelta
default:"timedelta(seconds=30)"
Timeout for API requests.
debug
bool
default:"False"
Enable debug logging for HTTP requests.
headers
dict[str, str] | None
Custom HTTP headers.
transport
httpx.AsyncHTTPTransport | None
Shared httpx transport (pool/proxy/retry).
use_server_proxy
bool
default:"False"
Use sandbox server as proxy for execd/endpoint requests.

Synchronous API

The SDK also provides synchronous versions of the main classes:
from opensandbox import SandboxSync, SandboxManagerSync
from opensandbox.config import ConnectionConfigSync

config = ConnectionConfigSync(
    domain="api.opensandbox.io",
    api_key="your-api-key"
)

sandbox = SandboxSync.create("ubuntu", connection_config=config)
with sandbox:
    execution = sandbox.commands.run("echo 'Hello Sandbox!'")
    print(execution.logs.stdout[0].text)
    sandbox.kill()
All async methods have synchronous equivalents in the SandboxSync, SandboxManagerSync, and ConnectionConfigSync classes.

Exception Handling

The SDK raises SandboxException and its subclasses for various error conditions:
from opensandbox.exceptions import (
    SandboxException,
    SandboxReadyTimeoutException,
    InvalidArgumentException,
)

try:
    sandbox = await Sandbox.create("python:3.11")
except SandboxReadyTimeoutException:
    print("Sandbox did not become ready in time")
except SandboxException as e:
    print(f"Sandbox error: [{e.error.code}] {e.error.message}")

Complete Example

import asyncio
from opensandbox import Sandbox
from opensandbox.config import ConnectionConfig
from opensandbox.models.execd import ExecutionHandlers
from datetime import timedelta

async def main():
    config = ConnectionConfig(
        domain="api.opensandbox.io",
        api_key="your-api-key"
    )

    async with await Sandbox.create(
        "python:3.11",
        timeout=timedelta(minutes=30),
        connection_config=config
    ) as sandbox:
        # Write a file
        await sandbox.files.write_file("script.py", "print('Hello World')")

        # Execute command with streaming
        handlers = ExecutionHandlers(
            on_stdout=lambda msg: print(f"Output: {msg.text}")
        )
        result = await sandbox.commands.run(
            "python script.py",
            handlers=handlers
        )

        # Get metrics
        metrics = await sandbox.get_metrics()
        print(f"Memory: {metrics.memory_used_in_mib}MB")

        # Cleanup
        await sandbox.kill()

if __name__ == "__main__":
    asyncio.run(main())

Build docs developers (and LLMs) love