Skip to main content
Optional extras:

What the Python SDK gives you

The BoxLite Python SDK lets you run any command, Python code, browser session, or desktop session inside an isolated microVM sandbox in a few lines of code, combining Docker-like ergonomics with VM-level isolation boundaries. This page is the authoritative, user-facing API reference — use it to look up how a class is constructed, what parameters a method accepts, what it returns, and which exceptions it may raise. Typical use cases: running untrusted code, giving an AI agent a disposable execution environment, isolating CI jobs, and automating a browser or desktop.

Quick Example (minimal happy path)

The following can be copied and run directly. SimpleBox is the recommended entry path and supports lazy creation and automatic cleanup.

Parameters & Returns (core API reference)

Package entry and exports

The main symbols importable via the top-level from boxlite import ...:
Note: AdvancedBoxOptions is exported at the top level — from boxlite import AdvancedBoxOptions (see 4.7 Security options).

Boxlite (runtime handle)

The runtime is responsible for creating, querying, and removing sandboxes. It is a synchronous context manager (with, not async with), but its data methods are asynchronous — create / get / get_info / list_info / remove / metrics / shutdown and similar return an _asyncio.Future and must be awaited inside an event loop (a plain for info in runtime.list_info() raises RuntimeError: no running event loop). Only close() releases the runtime synchronously.
Note: call await runtime.list_info() inside an async def. In addition, only one runtime instance can exist for a given BOXLITE_HOME (default ~/.boxlite) at a time — constructing a second one (for example, calling Boxlite.default() and then Boxlite(Options(...)) without first calling close() on the former) raises RuntimeError: ... Another BoxliteRuntime is already using directory.
Constructors and factories: Instance methods: Property: images (image handle: images.list() / images.pull(reference)).

Options (runtime configuration)

Options configures the runtime itself (not an individual sandbox) and is passed to Boxlite(...) / Boxlite.init_default(...).
The home_dir directory holds the on-disk state for the runtime:
home_dir set in Options takes precedence over the default location. The BOXLITE_HOME environment variable provides the same override without code changes; use one or the other.

Box (native sandbox handle, async context manager)

Box is the low-level handle. It is an async context manager (async with); every method must be awaited, info() included. Properties: id, name, snapshot (SnapshotHandle).
For most cases, prefer a high-level wrapper such as SimpleBox over the bare Box; the wrapper handles the env dict→list conversion, stdout/stderr collection, and timeout conversion automatically.

BoxOptions (sandbox configuration)

On the cpus / memory_mib defaults: when unset, the SDK passes None and the runtime applies 1 vCPU / 1024 MiB (vm_defaults in src/boxlite/src/runtime/constants.rs). The module-level DEFAULT_CPUS / DEFAULT_MEMORY_MIB constants are reference values and are not applied on this path. Production code should pass these values explicitly. See Compute resources.
NetworkSpec:

Volumes

The third element is a bool read_only (True = read-only / False = read-write), not the string "ro" / "rw". A 2-tuple also works (defaults to read-write).
The CLI’s -v host:box:ro string syntax belongs to the CLI parsing layer and differs from the SDK’s bool. Do not mix the two.

Security options (SecurityOptions + AdvancedBoxOptions)

Security configuration is passed via the advanced parameter; there is no top-level security= keyword. AdvancedBoxOptions is only available under the boxlite.boxlite module.
SecurityOptions presets (staticmethods):
There is no SecurityOptions.minimum(); the weak preset is called development().
AdvancedBoxOptions(security=None, health_check=None) also accepts a HealthCheckOptions.

Secrets (vault)

secrets is the real entry point for outbound credential substitution. For requests the sandbox sends to the specified hosts, BoxLite replaces placeholder with the real value, keeping plaintext credentials out of the sandbox filesystem.

SimpleBox (recommended entry, async context manager)

Validation on construction: at least one of image and rootfs_path must be provided, otherwise it raises ValueError. The sandbox is created lazily — create/start happens only when you enter the async with.
Methods: Properties: id (accessing before start raises RuntimeError), created (whether newly created; None before start).

CodeBox (Python code execution, subclass of SimpleBox)

Default image python:slim. Additional methods:
Also inherits all of SimpleBox’s exec/copy/start/stop/info. CodeBox.run’s timeout is an int, whereas SimpleBox.exec’s timeout is a float (inconsistent name/type).

Specialized box cheat sheet

All inherit from SimpleBox and are async context managers. See the dedicated topic pages for full method lists.
BrowserBox’s playwright_endpoint() (Playwright Server, all browsers) and endpoint() (direct CDP/BiDi, WebKit not supported) are two mutually exclusive modes.

ComputerBox desktop methods

All are async. Coordinates are in screen pixels; call get_screen_size() first if you need bounds.

InteractiveBox and SkillBox methods

Every other Box type also inherits exec / copy_in / copy_out / start / stop / shutdown / info from SimpleBox.

Execution / streaming output (returned by the low-level Box.exec)

Using Box.exec directly (not the SimpleBox wrapper) returns an Execution, which can be read as a stream:

ExecResult (returned by the high-level wrapper)

The dataclass returned by SimpleBox.exec / CodeBox.exec:
The low-level native Execution.wait() ExecResult only has exit_code (stdout/stderr must be read as streams); the high-level wrapper additionally fills in stdout/stderr.

BoxInfo / BoxStateInfo (state access)

box.info() is async and returns BoxInfo when awaited. State lives in a two-level structure:

Metrics (BoxMetrics / RuntimeMetrics)

Field names follow the source. BoxMetrics (await box.metrics()): RuntimeMetrics (runtime.metrics()):
metrics() exists only on the native Box (from boxlite import Box); SimpleBox has no metrics() method. A wrapper holds a native Box internally, so you can reach through with await box._box.metrics() — or use the native Box directly. For runtime-level metrics, use await runtime.metrics().

Exception types

Important: exec does not automatically raise ExecError on a non-zero exit — it returns ExecResult(exit_code != 0) and leaves the check to the caller. ExecError is a convenience exception you raise yourself after checking. Image pull failures, missing virtualization, and command not found (spawn failure) raise a standard RuntimeError (not BoxliteError; the message looks like internal error: spawn_failed: ... executable '...' not found in $PATH). When the sync/orchestration extras are missing: from boxlite import SyncSimpleBox raises ImportError, while attribute access boxlite.SyncSimpleBox raises AttributeError.

Sync API (boxlite[sync])

After pip install "boxlite[sync]", synchronous wrapper classes are available, suitable for Jupyter / existing synchronous code bases / a REPL. They cannot be used inside an existing event loop (inside an async function).
Note: when the [sync] extras are missing, from boxlite import SyncSimpleBox raises ImportError (cannot import name 'SyncSimpleBox' from 'boxlite'), not AttributeError. Only attribute access (boxlite.SyncSimpleBox) raises AttributeError. So when using the from ... import form, put the import in a try and catch ImportError:

REST client (connect to a remote BoxLite service)

BoxliteRestOptions(url, credential=None, path_prefix=None). path_prefix is an opaque, deployment-defined routing segment inserted as {url}/v1/{path_prefix}/…; leave it None for single-tenant deployments such as the local boxlite serve reference server. See the Node.js SDK reference for the full routing-prefix model.

Troubleshooting

Passing a string for a volume causes a TypeError

Wrong: writing the third volume element as the string "ro" / "rw".
Fix: use the bool read_only for the third element (True = read-only / False = read-write), or use a 2-tuple (defaults to read-write).

AttributeError: module 'boxlite' has no attribute 'AdvancedBoxOptions'

AdvancedBoxOptions lives in the boxlite.boxlite submodule, not the top level — see Inject secrets and harden a box.

AttributeError: ... 'security' (passing security= at the top level)

BoxOptions has no top-level security= keyword. Security options must go through advanced:

AttributeError: ... 'minimum'

SecurityOptions.minimum() does not exist. The available presets are development() / standard() / maximum().

exec reports a failed command but does not raise

A non-zero exit from exec returns ExecResult(exit_code != 0) and does not raise. Always check it yourself:

A metric field does not exist (AttributeError on memory_usage_bytes / cpu_time_ms / active_boxes)

The old field names are deprecated. Use BoxMetrics.memory_bytes, BoxMetrics.cpu_percent, and RuntimeMetrics.num_running_boxes instead.

box.info() raises a coroutine error / await fails

info() is async; await it. Access state via box.info().state.status (not .status, not .state.state).

RuntimeError on box start (environment constraint)

The sandbox requires hardware virtualization: Without virtualization, startup fails and raises RuntimeError (the process stays alive; handle it with try/except). A flaky network during image pull also raises RuntimeError and can be retried.

ImportError / AttributeError on sync classes

Sync/orchestration classes are exported on demand; when the extras are missing (with no friendly message):
  • from boxlite import SyncSimpleBox → ImportError (cannot import name 'SyncSimpleBox' from 'boxlite')
  • boxlite.SyncSimpleBox (attribute access) → AttributeError (module 'boxlite' has no attribute 'SyncSimpleBox')
Install the matching extras: pip install "boxlite[sync]" or pip install "boxlite[orchestration]".