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

# Python

> Run Python scripts on box

Run Python scripts inside the container on the specified box for test automation, hardware control, and data processing.

## Syntax

```bash theme={null}
lager python [OPTIONS] [RUNNABLE] [ARGS]...
```

## Global Options

| Option | Short | Type | Default | Description |
| - | - | - | - | - |
| `--box TEXT` | | String | | Lager Box name or IP address |
| `--env FOO=BAR` | | Multiple | | Set environment variables for the script |
| `--passenv VAR` | | Multiple | | Pass environment variables from current shell |
| `--kill TEXT` | | String | | Kill a specific running process by its process ID |
| `--kill-all` | | Flag | | Kill all running scripts |
| `--signal SIGNAL` | | Choice | `SIGTERM` | Signal to use with `--kill`/`--kill-all` |
| `--download` | | Flag | | When the script finishes, copy every file it wrote to `lager.output_dir()`, and the run record, to a new folder named after the run (see [File Downloads](#file-downloads)) |
| `--timeout SECONDS` | | Integer | 0 (none) | Maximum runtime in seconds. The box caps an attached run at 300; with `--detach` no cap applies |
| `--detach` | `-d` | Flag | | Run in detached mode (background) |
| `--port PORT` | `-p` | Multiple | | Forward ports to the Python process |
| `--add-file FILE` | | Multiple | | Add extra files to upload with script |
| `--reattach TEXT` | | String | | Reattach to a detached process by its process ID |
| `--continue TEXT` | | String | | Resume a script paused at a breakpoint, by its process ID |
| `--console TEXT` | | String | | Connect to the interactive console of a paused script, by its process ID |
| `--label KEY=VALUE` | | Multiple | | Add a label to the run record, for example an execution ID |
| `--help` | | Flag | | Show help message and exit |

**Arguments:**

* `RUNNABLE` - Python script file or directory to execute (required unless a process-management flag such as `--kill`, `--kill-all`, `--reattach`, `--continue`, or `--console` is used)
* `ARGS` - Additional arguments passed to the script

**Signal choices for `--kill`/`--kill-all`:** SIGINT, SIGQUIT, SIGABRT, SIGKILL, SIGUSR1, SIGUSR2, SIGTERM, SIGSTOP

## Basic Usage

```bash theme={null}
# Run a Python script on the box
lager python script.py --box my-lager-box

# Run with arguments
lager python test.py --box my-lager-box -- --verbose --target DUT1

# Run a directory as a module
lager python my_test_suite/ --box my-lager-box
```

## Environment Variables

### Setting Variables

```bash theme={null}
# Set explicit environment variables
lager python test.py --box my-lager-box --env API_KEY=abc123 --env DEBUG=true

# Pass variables from your current shell
export SECRET_TOKEN=xyz
lager python test.py --box my-lager-box --passenv SECRET_TOKEN
```

### Auto-Injected Variables

The following environment variables are automatically available inside your script:

| Variable | Description |
| - | - |
| `LAGER_OUTPUT_CHANNEL` | File path for structured output (see Structured Output below) |
| `LAGER_PROCESS_ID` | Unique UUID for this execution |
| `LAGER_RUNNABLE` | Path to the script being executed |
| `LAGER_BOX` | Box name (if `--box` was provided) |
| `LAGER_RUN_ASSERTIONS` | File that `lager.record_value()` writes to (see Run Record below) |
| `LAGER_OUTPUT_DIR` | The run's output folder, which `lager.output_dir()` returns (see File Downloads below) |

## File Downloads

Each run has its own output folder on the box. Write the files your script
makes to `lager.output_dir()`:

```python theme={null}
import os
from lager import output_dir

with open(os.path.join(output_dir(), 'results.csv'), 'w') as f:
    f.write('step,voltage\n1,4.2027\n')
```

Then add `--download` to get all of them back:

```bash theme={null}
lager python test.py --box my-lager-box --download
```

When the script finishes, the CLI makes a new folder in the current directory,
named after the run. It copies into that folder every file the script wrote to
`lager.output_dir()`, with any subfolders, and the run record. The CLI then
compares each file with the hash in the record:

```
3f6c2a9e-8d41-4b7a-9e2f-1c5d7b0a6e13/
├── results.csv
└── 3f6c2a9e-8d41-4b7a-9e2f-1c5d7b0a6e13.lager-run.json
```

The run record lists every file in the output folder, with or without
`--download`. Without `--download`, the CLI does not save anything on your
computer. Outside `lager python`, `lager.output_dir()` returns a `lager-output`
folder in the current directory, so the script still runs on your computer.

## Detached Mode

Run scripts in the background without waiting for output:

```bash theme={null}
# Start a long-running script in the background
lager python long_running.py --box my-lager-box --detach
```

In detached mode:

* The command returns as soon as the box accepts the job. It returns before the
  script starts, and before any setup that the script needs (unpacking a module
  directory, installing its `requirements.txt`)
* No stdout/stderr is streamed back
* The script continues running on the box
* Use `--reattach` to see its output, `--kill` to stop it later

The launch returns before the setup runs. A job can therefore fail to start
after the prompt comes back -- a `requirements.txt` that will not install, say.
You see that failure through the job, not at the prompt. `--reattach` shows the
failure and exits non-zero:

```bash theme={null}
lager python ./my_module --box my-lager-box --detach
# Process detached (Process ID: 7f3c...)

lager python --reattach 7f3c... --box my-lager-box
# ERROR: Could not find a version that satisfies the requirement ...
# Process exited with code 1
```

A detached run takes the box lock. A box on 0.42.0 or later then holds that lock
while the job runs, and releases it when the job ends. The CLI prints
`Box 'my-lager-box' is held for the detached run and released when it ends`.
An older box keeps the lock after the job ends. The CLI then prints
`release with: lager boxes unlock --box my-lager-box`. See
[locking](https://docs.lagerdata.com/source/reference/cli/locking.md).

## Killing Running Scripts

`--kill` takes the process ID that the detached launch printed.

```bash theme={null}
# Kill with default SIGTERM
lager python --kill <PROCESS_ID> --box my-lager-box
# Process <PROCESS_ID> killed

# Kill with specific signal
lager python --kill <PROCESS_ID> --signal SIGKILL --box my-lager-box

# Kill every running script
lager python --kill-all --box my-lager-box
# All processes killed
```

## Port Forwarding

Forward network ports from the box to your local machine:

```bash theme={null}
# Forward port 8080
lager python web_server.py --box my-lager-box -p 8080

# Forward with different local/remote ports
lager python server.py --box my-lager-box -p 8080:80

# Forward with protocol
lager python server.py --box my-lager-box -p 8080:80/tcp
```

Port format: `SRC_PORT[:DST_PORT][/PROTOCOL]`

## Timeout

Limit script execution time:

```bash theme={null}
# Kill after 5 minutes
lager python analysis.py --box my-lager-box --timeout 300
```

* `0`, the default, means no limit.
* An attached run is capped at 300 seconds. A larger value runs for 300 seconds,
  and the box writes the cap to its log.
* A detached run has no cap. The box applies the value only when you give one.

When a script exceeds the timeout, the box sends the signals:

* First, SIGTERM is sent. The CLI prints `Script terminated due to timeout.` and
  exits with code 124
* If the script does not exit within 5 seconds, SIGKILL is sent. The CLI prints
  `Script forcibly killed due to timeout.` and exits with code 137

## Structured Output

Scripts running on the box can send structured data back to the CLI using the `lager.core.output()` function. This uses a dedicated output channel (file descriptor 3) separate from stdout/stderr.

### Box-Side API

```python theme={null}
from lager.core import output, OutputEncoders

# Output a Python dict (default: pickle encoding)
output({'status': 'pass', 'measurement': 3.14})

# Output as JSON
output({'voltage': 3.3, 'current': 0.5}, encoder=OutputEncoders.JSON)

# Output as YAML
output({'device': 'PSU-1', 'readings': [1.0, 2.0]}, encoder=OutputEncoders.YAML)

# Output raw binary data
output(image_bytes, encoder=OutputEncoders.Raw)
```

**Available encoders:**

| Encoder | ID | Use Case |
| - | - | - |
| `OutputEncoders.Raw` | 1 | Binary data (images, files) |
| `OutputEncoders.Pickle` | 2 | Python objects (default) |
| `OutputEncoders.JSON` | 3 | JSON-serializable data |
| `OutputEncoders.YAML` | 4 | YAML-serializable data |

Structured output is printed to the CLI console as it arrives. Standard stdout and stderr are streamed separately in real time.

## Module Includes

If your script depends on local modules, configure includes in a `.lager` file in your project. The file is JSON:

```json theme={null}
{
  "includes": {
    "my_lib": "../my_lib",
    "fixtures": "/path/to/fixtures"
  }
}
```

A relative path is relative to the `.lager` file. The CLI starts at the directory of the script, and searches up the directory tree for a `.lager` file. It then zips the script along with all include directories before uploading to the box.

```bash theme={null}
# Script can import from included directories
lager python test.py --box my-lager-box
```

In `test.py`:

```python theme={null}
from my_lib import helpers
from fixtures import test_data
```

## Additional Files

Upload extra files alongside your script:

```bash theme={null}
lager python flash_and_test.py --box my-lager-box --add-file firmware.hex --add-file config.json
```

Files are available in the same directory as your script on the box.

## Exit Codes

| Exit Code | Meaning |
| - | - |
| 0 | Success |
| 255 | The CLI did not get the exit code from the box. It prints `Failed to retrieve script exit code.` |
| 124 | Script terminated by SIGTERM (timeout) |
| 137 | Script killed by SIGKILL (timeout, force) |
| 128+N | Script stopped by signal N |
| Other | Script's own exit code |

## Run Record

The box writes a run record for each run. The record is a JSON file. It shows
what ran, on which box, in which state, and what came out:

* The SHA-256 hash of each file that the box received
* The box state when the run started: the Lager version, the OS, the net
  configuration, and the serial number of each instrument
* The start time, the end time, and the exit code
* Why the run ended: it exited, it timed out, it was cancelled, or the client
  disconnected
* The SHA-256 hash of the output and of each file in the run's output folder

Where the record is kept:

* **On the box, for every run.** The box keeps the records of its most recent
  500 runs.
* **In the box's outbox, if a collector manages the box.** A collector is a
  service that takes each record from the box and keeps it somewhere else.
  These records stay in the outbox until the collector takes them.
* **On your computer, only with `--download`.** The CLI writes the record as
  `<process-id>.lager-run.json` in the run's folder, next to the downloaded
  files (see [File Downloads](#file-downloads)). The CLI compares the output
  and the downloaded files with the hashes in the record. If they are
  different, the CLI shows a warning.

Add labels to find a run later:

```bash theme={null}
lager python test.py --box my-lager-box --label execution=EX-20419
```

A script can add values that only the script knows, for example the firmware
version of the device under test:

```python theme={null}
from lager import record_value

record_value('dut.firmware', '2.14.0')
```

The box does not verify labels or values from a script. Do not put secrets in
them. For the full format, see `docs/reference/run-record.md` in the Lager
repository.

## Box Lock

`lager python` takes the box lock when it runs a script. Another user then cannot
drive the same box at the same time. See [locking](https://docs.lagerdata.com/source/reference/cli/locking.md).

* An attached run holds the lock while the script runs. The command releases it
  when it exits.
* If another user holds the lock, the command fails at once on your computer. In
  CI, it waits for the lock.
* `--kill`, `--kill-all`, `--reattach`, `--continue`, and `--console` do not take
  the lock.
* Set `LAGER_AUTO_LOCK_DISABLE=1` to run without the lock.

## Examples

```bash theme={null}
# Basic script execution
lager python script.py --box my-lager-box

# Run with environment variables
lager python test.py --box my-lager-box --env API_KEY=abc123 --env DEBUG=true

# Run in detached mode
lager python long_running.py --box my-lager-box --detach

# Download the run's output files and record after completion
lager python data_processor.py --box my-lager-box --download

# Kill running script
lager python --kill <PROCESS_ID> --box my-lager-box

# Run with port forwarding
lager python web_server.py --box my-lager-box -p 8080

# Run with timeout
lager python analysis.py --box my-lager-box --timeout 300

# Upload extra files with script
lager python flash_test.py --box my-lager-box --add-file firmware.hex

# Pass arguments to the script
lager python test.py --box my-lager-box -- --device DUT1 --verbose
```

### Hardware Test Script Example

```python theme={null}
# test_power.py - run with: lager python test_power.py --box my-lager-box
from lager import Net, NetType
from lager.core import output, OutputEncoders
import time

# Get the power supply net
psu = Net.get("PSU_CH1", type=NetType.PowerSupply)

# Set voltage and enable
psu.voltage(value=3.3, ovp=3.6)
psu.enable()
time.sleep(1)

# Read state
state = psu.get_full_state()
print(f"Voltage: {state['voltage']}V, Current: {state['current']}A")

# Send structured results
output({
    'test': 'power_on',
    'voltage': state['voltage'],
    'current': state['current'],
    'status': 'pass' if state['voltage'] > 3.0 else 'fail'
}, encoder=OutputEncoders.JSON)

# Cleanup
psu.disable()
```

## Notes

* Use `--env` for script-specific configuration values
* Use `--passenv` for secrets/tokens from your current shell
* `--download` retrieves files only after script completion (not during), and only the files in `lager.output_dir()`
* Port forwarding syntax: `SRC_PORT[:DST_PORT][/PROTOCOL]`
* Output is streamed in real time via a multiplexed HTTP protocol with keepalive (20-second interval)

***

## Installing Python packages

Scripts run inside the Lager Python container on the box. To install the
packages that your scripts depend on, use the declarative `lager box-config pip`
commands. Those commands record the packages in the box config and rebuild the
container. The packages then persist across `lager python` runs and box updates.

```bash theme={null}
# Add one or more packages
lager box-config pip add pandas requests --box my-box

# List configured packages
lager box-config pip list --box my-box

# Remove a package
lager box-config pip remove numpy --box my-box

# Apply the changes (rebuild the container)
lager box-config apply --box my-box
```

See the [Box Config reference](https://docs.lagerdata.com/source/reference/cli/box-config.md) for the full
declarative provisioning workflow (pip/cargo/npm packages, apt, udev, mounts,
env, and more).

> [!NOTE]
>
> The standalone `lager pip` command was removed and folded into
> `lager box-config pip`.


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.