> ## Documentation Index
> Fetch the complete documentation index at: https://docs.boxlite.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Python SDK

> BoxLite Python SDK reference

Complete API reference for the BoxLite Python SDK.

**Python:** 3.10+
**Platforms:** macOS (Apple Silicon), Linux (x86\_64, ARM64)

## Installation

```bash theme={null}
pip install boxlite
```

For the sync API (greenlet-based):

```bash theme={null}
pip install boxlite[sync]
```

## Runtime Management

### `boxlite.Boxlite`

The main runtime for creating and managing boxes.

```python theme={null}
from boxlite import Boxlite, Options, BoxOptions
```

#### Class Methods

| Method       | Signature                       | Description                                         |
| ------------ | ------------------------------- | --------------------------------------------------- |
| `default()`  | `() -> Boxlite`                 | Create runtime with default settings (`~/.boxlite`) |
| `__init__()` | `(options: Options) -> Boxlite` | Create runtime with custom options                  |

#### Instance Methods

| Method      | Signature                                        | Description                               |
| ----------- | ------------------------------------------------ | ----------------------------------------- |
| `create()`  | `(options: BoxOptions, name: str = None) -> Box` | Create a new box (async)                  |
| `get()`     | `(box_id: str) -> Box`                           | Reattach to an existing box by ID (async) |
| `list()`    | `() -> List[BoxInfo]`                            | List all boxes (async)                    |
| `metrics()` | `() -> RuntimeMetrics`                           | Get runtime-wide metrics (async)          |

#### Example

```python theme={null}
# Default runtime
runtime = Boxlite.default()

# Custom runtime
runtime = Boxlite(Options(home_dir="/custom/path"))

# Create a box
box = await runtime.create(BoxOptions(image="alpine:latest"))

# List all boxes
for info in await runtime.list():
    print(f"{info.id}: {info.status}")
```

### `boxlite.Options`

Runtime configuration options.

| Field              | Type        | Default      | Description                                        |
| ------------------ | ----------- | ------------ | -------------------------------------------------- |
| `home_dir`         | `str`       | `~/.boxlite` | Base directory for runtime data                    |
| `image_registries` | `List[str]` | `[]`         | Custom image registries for unqualified references |

### `boxlite.BoxOptions`

Configuration options for creating a box.

| Field          | Type                          | Default   | Description                                              |
| -------------- | ----------------------------- | --------- | -------------------------------------------------------- |
| `image`        | `str`                         | Required  | OCI image URI (e.g., `"python:slim"`, `"alpine:latest"`) |
| `cpus`         | `int`                         | `1`       | Number of CPU cores (1 to host CPU count)                |
| `memory_mib`   | `int`                         | `2048`    | Memory limit in MiB (128-65536)                          |
| `disk_size_gb` | `int \| None`                 | `None`    | Persistent disk size in GB (None = ephemeral)            |
| `working_dir`  | `str`                         | `"/root"` | Working directory inside container                       |
| `env`          | `List[Tuple[str, str]]`       | `[]`      | Environment variables as (key, value) pairs              |
| `volumes`      | `List[Tuple[str, str, bool]]` | `[]`      | Volume mounts as (host\_path, guest\_path, read\_only)   |
| `ports`        | `List[Tuple[int, int, str]]`  | `[]`      | Port forwarding as (host\_port, guest\_port, protocol)   |
| `auto_remove`  | `bool`                        | `True`    | Auto cleanup when stopped                                |
| `detach`       | `bool`                        | `False`   | Survive parent process exit                              |

#### Volume Mount Format

```python theme={null}
volumes=[
    ("/host/config", "/etc/app/config", True),   # Read-only
    ("/host/data", "/mnt/data", False),           # Read-write
]
```

#### Port Forwarding Format

```python theme={null}
ports=[
    (8080, 80, "tcp"),    # HTTP
    (5432, 5432, "tcp"),  # PostgreSQL
    (53, 53, "udp"),      # DNS
]
```

## Box Handle

### `boxlite.Box`

Handle to a running or stopped box.

#### Properties

| Property | Type  | Description                         |
| -------- | ----- | ----------------------------------- |
| `id`     | `str` | Unique box identifier (ULID format) |

#### Methods

| Method      | Signature                            | Description                        |
| ----------- | ------------------------------------ | ---------------------------------- |
| `exec()`    | `(cmd, args, env, tty) -> Execution` | Execute command (async)            |
| `stop()`    | `() -> None`                         | Stop the box gracefully (async)    |
| `remove()`  | `() -> None`                         | Delete box and its data (async)    |
| `info()`    | `() -> BoxInfo`                      | Get box metadata (sync)            |
| `metrics()` | `() -> BoxMetrics`                   | Get resource usage metrics (async) |

### `boxlite.BoxInfo`

Metadata about a box.

| Field        | Type          | Description                                           |
| ------------ | ------------- | ----------------------------------------------------- |
| `id`         | `str`         | Unique box identifier (ULID)                          |
| `name`       | `str \| None` | Optional user-assigned name                           |
| `status`     | `str`         | Current status: `"running"`, `"stopped"`, `"created"` |
| `created_at` | `datetime`    | Creation timestamp                                    |
| `pid`        | `int \| None` | Process ID (if running)                               |
| `image`      | `str`         | OCI image used                                        |
| `cpus`       | `int`         | Allocated CPU cores                                   |
| `memory_mib` | `int`         | Allocated memory in MiB                               |

### `boxlite.BoxStateInfo`

Detailed state information for a box.

| Value      | Description                     |
| ---------- | ------------------------------- |
| `Created`  | Box created but not yet started |
| `Starting` | Box is initializing             |
| `Running`  | Box is running and ready        |
| `Stopping` | Box is shutting down            |
| `Stopped`  | Box is stopped                  |
| `Failed`   | Box encountered an error        |

## Sync API

Synchronous wrappers using greenlet fiber switching. Requires `pip install boxlite[sync]`.

```python theme={null}
from boxlite import SyncBoxlite, SyncBox, SyncSimpleBox, SyncCodeBox
```

### When to Use

| Use Case               | API                 |
| ---------------------- | ------------------- |
| New async applications | Async API (default) |
| Existing sync codebase | Sync API            |
| Jupyter notebooks      | Sync API            |
| REPL/interactive use   | Sync API            |
| Inside async functions | Async API only      |

### Comparison Table

| Async API    | Sync API         | Notes            |
| ------------ | ---------------- | ---------------- |
| `Boxlite`    | `SyncBoxlite`    |                  |
| `Box`        | `SyncBox`        |                  |
| `Execution`  | `SyncExecution`  |                  |
| `ExecStdout` | `SyncExecStdout` | Regular iterator |
| `ExecStderr` | `SyncExecStderr` | Regular iterator |
| `SimpleBox`  | `SyncSimpleBox`  |                  |
| `CodeBox`    | `SyncCodeBox`    |                  |

### Classes

#### `SyncBoxlite`

```python theme={null}
from boxlite import SyncBoxlite, BoxOptions

with SyncBoxlite.default() as runtime:
    box = runtime.create(BoxOptions(image="alpine:latest"))
    execution = box.exec("echo", ["Hello"])
    for line in execution.stdout():
        print(line)
    box.stop()
```

#### `SyncSimpleBox`

```python theme={null}
from boxlite import SyncSimpleBox

with SyncSimpleBox(image="python:slim") as box:
    result = box.exec("python", "-c", "print('Hello!')")
    print(result.stdout)
```

#### `SyncCodeBox`

```python theme={null}
from boxlite import SyncCodeBox

with SyncCodeBox() as cb:
    result = cb.run("print('Hello, World!')")
    print(result)
```

### Architecture

The sync API uses greenlet fiber switching:

1. A dispatcher fiber runs the asyncio event loop
2. User code runs in the main fiber
3. Sync methods switch to dispatcher, await async operations, then switch back

<Warning>
  The sync API cannot be used inside an async context (when an event loop is already running).
</Warning>

## Constants

Default values used by BoxLite.

| Constant                     | Value  | Description                     |
| ---------------------------- | ------ | ------------------------------- |
| `DEFAULT_CPUS`               | `1`    | Default CPU cores               |
| `DEFAULT_MEMORY_MIB`         | `2048` | Default memory in MiB           |
| `COMPUTERBOX_CPUS`           | `2`    | ComputerBox default CPUs        |
| `COMPUTERBOX_MEMORY_MIB`     | `2048` | ComputerBox default memory      |
| `COMPUTERBOX_DISPLAY_WIDTH`  | `1024` | Screen width in pixels          |
| `COMPUTERBOX_DISPLAY_HEIGHT` | `768`  | Screen height in pixels         |
| `COMPUTERBOX_GUI_HTTP_PORT`  | `3000` | HTTP GUI port                   |
| `COMPUTERBOX_GUI_HTTPS_PORT` | `3001` | HTTPS GUI port                  |
| `DESKTOP_READY_TIMEOUT`      | `60`   | Desktop ready timeout (seconds) |

## See Also

* [Box Types](/reference/python/box-types) - SimpleBox, CodeBox, BrowserBox, ComputerBox, InteractiveBox
* [Execution](/reference/python/execution) - Command execution, streaming I/O, stdin/stdout/stderr
* [Errors & Metrics](/reference/python/errors-metrics) - Exception hierarchy, metrics classes
* [Getting Started](/getting-started/index) - Installation and quickstart guide
* [Configuration Reference](/reference/index) - BoxOptions details
