---
title: Sandboxes SDK tutorial
description: 'A sandbox is a lightweight, programmable execution environment for commands,'
canonical: 'https://lightning.ai/docs/sdk/stable/examples/sandboxes'
---
# Sandboxes SDK tutorial {#sandboxes-sdk-tutorial}

A sandbox is a lightweight, programmable execution environment for commands,
files, and short-lived runtime state. Use sandboxes for isolated code execution,
tool calls, temporary build steps, and workloads that do not need a full
persistent Studio.

Sandboxes use a sandbox API key. For teamspace-scoped operations, create a
teamspace API key in Lightning AI and provide it through the environment or the
SDK client configuration. Do not commit API keys to source control.

## Prerequisites {#prerequisites}

Install the package and configure a sandbox API key:

```console
$ pip install lightning-sdk -U
$ export LIGHTNING_SANDBOX_API_KEY="replace-at-runtime"
```

The SDK exposes a client and a sandbox instance handle. Create the sandbox,
write a file, run commands, and stop it from Python:

```python
sandbox = Sandbox.create(
    name=args.name,
    teamspace=args.teamspace,
    instance_type=args.instance_type,
    persistent=True,
)

print(f"Sandbox {sandbox.name}: {sandbox.sandbox_id}")

sandbox.write_file(
    "/workspace/app.py",
    "print('hello from a file inside the sandbox')\n",
)

command = sandbox.run_command(
    RunCommandOpts(
        cmd="python",
        args=["/workspace/app.py"],
        env={"MODE": "tutorial"},
    )
)
print(command.output)

auto_snapshot_id = sandbox.stop()
print(f"Auto snapshot: {auto_snapshot_id}")
```

Use the client object when you need to list, fetch, resume, or delete sandboxes
from reusable application code:

```python
client = Sandbox()

result = client.list(teamspace=args.teamspace, limit=10)
for sandbox in result.sandboxes:
    print(f"{sandbox.sandbox_id}: {sandbox.name} ({sandbox.status})")

sandbox = client.get(args.sandbox_id)
if sandbox.status == "paused":
    sandbox = sandbox.resume()

command = sandbox.run_command("python --version")
print(command.output)

sandbox.delete()
```

Run the companion script directly when you want to execute the SDK example:

```console
$ python python/examples/sandboxes.py --teamspace owner/teamspace create
$ python python/examples/sandboxes.py --teamspace owner/teamspace inspect --sandbox-id sbx_1234567890
```

## Operational notes {#operational-notes}

- `Sandbox.create` returns a running `SandboxInstance`.
- `persistent=True` lets `stop` capture an automatic snapshot that can be
  resumed later.
- `delete` destroys the sandbox and discards auto-snapshot state.
- `run_command` accepts either a command string plus args or a
  `RunCommandOpts` object for cwd, environment, detached execution, and other
  command settings.

---

**Navigation**

- Parent: [Examples](/docs/sdk/2026.11.04/examples.md)
