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
from boxlite import ...:
Note:AdvancedBoxOptionsis 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: callConstructors and factories:await runtime.list_info()inside anasync def. In addition, only one runtime instance can exist for a givenBOXLITE_HOME(default~/.boxlite) at a time — constructing a second one (for example, callingBoxlite.default()and thenBoxlite(Options(...))without first callingclose()on the former) raisesRuntimeError: ... Another BoxliteRuntime is already using directory.
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_dirset inOptionstakes precedence over the default location. TheBOXLITE_HOMEenvironment 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 asSimpleBoxover the bareBox; the wrapper handles the env dict→list conversion, stdout/stderr collection, and timeout conversion automatically.
BoxOptions (sandbox configuration)
On thecpus/memory_mibdefaults: when unset, the SDK passesNoneand the runtime applies 1 vCPU / 1024 MiB (vm_defaultsinsrc/boxlite/src/runtime/constants.rs). The module-levelDEFAULT_CPUS/DEFAULT_MEMORY_MIBconstants 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 boolread_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 noSecurityOptions.minimum(); the weak preset is calleddevelopment().
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 ofMethods:imageandrootfs_pathmust be provided, otherwise it raisesValueError. The sandbox is created lazily — create/start happens only when you enter theasync with.
Properties:
id (accessing before start raises RuntimeError), created (whether newly created; None before start).
CodeBox (Python code execution, subclass of SimpleBox)
python:slim. Additional methods:
Also inherits all ofSimpleBox’s exec/copy/start/stop/info.CodeBox.run’stimeoutis anint, whereasSimpleBox.exec’stimeoutis afloat(inconsistent name/type).
Specialized box cheat sheet
All inherit fromSimpleBox and are async context managers. See the dedicated topic pages for full method lists.
BrowserBox’splaywright_endpoint()(Playwright Server, all browsers) andendpoint()(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 inheritsexec/copy_in/copy_out/start/stop/shutdown/infofromSimpleBox.
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 nativeExecution.wait()ExecResultonly hasexit_code(stdout/stderr must be read as streams); the high-level wrapper additionally fills instdout/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 nativeBox(from boxlite import Box);SimpleBoxhas nometrics()method. A wrapper holds a nativeBoxinternally, so you can reach through withawait box._box.metrics()— or use the nativeBoxdirectly. For runtime-level metrics, useawait runtime.metrics().
Exception types
Important:execdoes not automatically raiseExecErroron a non-zero exit — it returnsExecResult(exit_code != 0)and leaves the check to the caller.ExecErroris a convenience exception you raise yourself after checking. Image pull failures, missing virtualization, and command not found (spawn failure) raise a standardRuntimeError(notBoxliteError; the message looks likeinternal error: spawn_failed: ... executable '...' not found in $PATH). When the sync/orchestration extras are missing:from boxlite import SyncSimpleBoxraisesImportError, while attribute accessboxlite.SyncSimpleBoxraisesAttributeError.
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 SyncSimpleBoxraisesImportError(cannot import name 'SyncSimpleBox' from 'boxlite'), notAttributeError. Only attribute access (boxlite.SyncSimpleBox) raisesAttributeError. So when using thefrom ... importform, put the import in atryand catchImportError:
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".
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. UseBoxMetrics.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')
pip install "boxlite[sync]" or pip install "boxlite[orchestration]".
