---
title: Python SDK · Sandboxes docs
description: The quietrobot-sandboxes package for Python 3.9 and newer: sandboxes, commands, code, files, preview URLs, snapshots and the rest.
url: https://www.quietrobot.ai/docs/sandboxes/python
---

# Python SDK

The quietrobot-sandboxes package for Python 3.9 and newer: sandboxes, commands, code, files, preview URLs, snapshots and the rest.

> [!NOTE]
> Sandboxes is in early access. It is free to try, some parts are still in testing, and details may change.

```bash
pip install quietrobot-sandboxes
export QR_API_KEY=qr_live_...
```

The package has no dependencies beyond the standard library, and it installs the [`qr` command](https://www.quietrobot.ai/docs/sandboxes/cli) too. Each method is one REST call, listed in the [API reference](https://www.quietrobot.ai/docs/sandboxes/api-reference).

## The client

```python
from quietrobot_sandboxes import Sandboxes

qr = Sandboxes()                       # reads QR_API_KEY, and QR_BASE_URL if set
qr = Sandboxes(api_key="qr_live_...")  # or pass it
```

The client keeps one connection open per thread and reuses it. `qr.close()` closes it. Requests honor `HTTPS_PROXY` and `NO_PROXY`.

## Create a sandbox

```python
with qr.create(
    template="base",                     # or "minimal", or one of your own templates
    cpus=2, memory_mb=2048,
    timeout_sec=1800,                    # lifetime; default 600
    region="us-virginia",
    egress={"mode": "allowlist", "allow": ["pypi.org", "files.pythonhosted.org"]},
    env={"MODE": "test"},
) as sbx:
    ...
# leaving the block destroys the sandbox
```

Without `with`, call `sbx.destroy()` yourself. `qr.get(id)` (or `qr.connect(id)`) picks up a sandbox started earlier, and `qr.list(status)` lists them.

## Commands

```python
run = sbx.exec("make test", cwd="work", env={"CI": "1"}, timeout_ms=120_000)
print(run["exitCode"], run["stdout"], run["stderr"])

# Stream output while it runs (up to an hour)
sbx.exec("pip install -r requirements.txt", on_stdout=print, timeout_ms=600_000)

# In the background: read output later, write to stdin, stop it
p = sbx.spawn("python3 -m http.server 8000")
p = sbx.spawn("python3 -i", interactive=True)
p.send_stdin("print(1 + 1)\n")
for stream, data in p:
    print(stream, data)
    break
p.kill()

# An interactive shell on a pseudo-terminal
t = sbx.terminal(cols=120, rows=40)
t.send_stdin("ls\n")
```

Relative paths and `cwd` are inside `/home/sandbox`. A command that exits non-zero isn't an exception: check `exitCode`.

When an [approval rule](https://www.quietrobot.ai/docs/sandboxes/approvals) holds a command, `exec` waits for a person's decision. Pass `wait_for_approval=False` to return at once with `status: "pending_approval"`, `approval_timeout` (seconds) to cap the wait, or `on_pending` to be told when a command starts waiting. A denied command raises `CommandDeniedError`.

## Code

A notebook-style Python kernel: variables persist between calls, the last line's value comes back, and matplotlib figures come back as base64 PNG. The code is part of the command, so your policy and the audit log see every cell.

```python
sbx.run_code("import pandas as pd\ndf = pd.DataFrame({'a': [1, 2, 3]})")
cell = sbx.run_code("df.a.sum()")
print(cell["results"][0]["text"])    # 6
if cell["error"]:
    print(cell["error"]["traceback"])
sbx.restart_code()                   # clears the variables
```

## Files

```python
sbx.files.write("data/in.csv", csv_text)     # str or bytes; folders are created
data = sbx.files.read("out/report.pdf")      # bytes
text = sbx.files.read_text("out/summary.txt")
sbx.files.list("data")
sbx.files.remove("data/in.csv")
```

## Preview URLs

```python
sbx.spawn("python3 -m http.server 8000")
port = sbx.ports.expose(8000)          # private: port["shareUrl"] opens it in a browser
sbx.ports.expose(3000, "public")       # anyone with the URL
print(sbx.host(8000))                  # 8000-sbx-....quietrobot.dev
sbx.ports.close(3000)
```

## Pause, snapshots, fork and rewind

```python
sbx.pause()                            # memory and running processes kept; paused time isn't billed
sbx.resume()

snap = sbx.snapshot("with-deps")       # the home folder, including packages installed there
copies = sbx.fork(count=3)             # three copies of this machine as it is now
big = sbx.fork(cpus=4, memory_mb=8192)["sandboxes"][0]  # resize: a bigger copy
sbx.rewind(snapshot_id=snap["id"])     # files back as they were
fresh = qr.create(snapshot_id=snap["id"])
```

See [Pause and resume](https://www.quietrobot.ai/docs/sandboxes/pause-and-resume) and [Snapshots](https://www.quietrobot.ai/docs/sandboxes/snapshots).

## Everything else

| Call | |
|---|---|
| `sbx.set_timeout(sec)` | Resets the deadline to now plus `sec`. |
| `sbx.set_egress(mode=, allow=, deny=)` | Changes the network rules while it runs. |
| `sbx.metrics(hours)` | CPU, memory, disk and network readings. |
| `sbx.executions()`, `sbx.audit()` | This sandbox's commands and audit events. |
| `sbx.sync_volumes()` | Saves attached volumes now. |
| `qr.audit()`, `qr.usage(days)` | The organization's audit log and usage. |
| `qr.snapshots()`, `qr.delete_snapshot(id)` | Snapshots. |
| `qr.secrets()`, `qr.set_secret(name, value, hosts)`, `qr.delete_secret(name)` | [Secrets](https://www.quietrobot.ai/docs/sandboxes/secrets) a sandbox can use without holding them. |
| `qr.volumes()`, `qr.create_volume(name)`, `qr.delete_volume(id)` | Folders kept between sandboxes. |
| `qr.webhooks()`, `qr.create_webhook(url, events)` and the rest | Lifecycle events sent to your URL. Check them with `verify_webhook(secret, headers, body)`. |

## Errors

Errors raise `SandboxesError` with `.status`, `.code` and `.message`; the codes are on [Errors](https://www.quietrobot.ai/docs/sandboxes/errors). A `429` from the rate limit also sets `.retry_after` in seconds.

```python
from quietrobot_sandboxes import SandboxesError

try:
    qr.create(cpus=16)
except SandboxesError as e:
    print(e.status, e.code, e.message)   # 403 plan_limit The Free plan allows up to 2 vCPUs
```

## Agent frameworks and E2B

`quietrobot_sandboxes.integrations` gives an agent six tools on one sandbox (for the OpenAI Agents SDK, LangChain, or as plain functions), and `quietrobot_sandboxes.e2b` is a drop-in for E2B's `Sandbox`. See [Agent frameworks, E2B and CI](https://www.quietrobot.ai/docs/sandboxes/integrations).
