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

# Run commands in a sandbox

> Run terminal commands inside a sandbox, read stdout and stderr, start background processes, override environment variables, and stream output as it arrives.

`commands.run()` runs terminal commands inside a sandbox. It returns the command output, can start a process in the background, and can stream output through callbacks as the process produces it.

> [!NOTE]
>
> Install the SDK, or the CLI for `ppio` commands, and set the `PPIO_API_KEY` and `PPIO_DOMAIN` environment variables before running these examples. See [Quickstart](https://docs.ppio.ai/sandbox/quickstart.md) and [Install and authenticate](https://docs.ppio.ai/sandbox/cli/install.md).

## Run a command

Call `commands.run()` with a command string. The returned result contains the command output. In the CLI examples, `<sandbox-id>` is the sandbox ID.

```python Python theme={null}
from ppio_sandbox import PPIO

ppio = PPIO()
sandbox = ppio.sandbox.create()

result = sandbox.commands.run('ls -l')
print(result)

sandbox.kill()
```

```javascript Node.js theme={null}
import { PPIO } from 'ppio-sandbox'

const ppio = new PPIO()
const sandbox = await ppio.sandbox.create()

const result = await sandbox.commands.run('ls -l')
console.log(result)

await sandbox.kill()
```

```bash CLI theme={null}
# Execute a command in a running sandbox (alias: sandbox ex)
ppio sandbox exec <sandbox-id> echo "hello"

# Run in background
ppio sandbox exec <sandbox-id> -b long-running-cmd

# Set working directory / user / env
ppio sandbox exec <sandbox-id> -c /home/user -u root -e KEY=VALUE "ls -la"
```

## Read the command output

Use `stdout` to read what the command printed.

```python Python theme={null}
from ppio_sandbox import PPIO

ppio = PPIO()
sandbox = ppio.sandbox.create()

result = sandbox.commands.run("echo hello")
print(result.stdout)   # hello

sandbox.kill()
```

```javascript Node.js theme={null}
import { PPIO } from 'ppio-sandbox'

const ppio = new PPIO()
const sandbox = await ppio.sandbox.create()

const result = await sandbox.commands.run('echo hello')
console.log(result.stdout) // hello

await sandbox.kill()
```

## Run a command in the background

Pass the background option to start a long-running process, such as a server, without blocking on it.

```python Python theme={null}
from ppio_sandbox import PPIO

ppio = PPIO()
sandbox = ppio.sandbox.create()

sandbox.commands.run("python3 -m http.server 3000", background=True)

sandbox.kill()
```

```javascript Node.js theme={null}
import { PPIO } from 'ppio-sandbox'

const ppio = new PPIO()
const sandbox = await ppio.sandbox.create()

await sandbox.commands.run('python3 -m http.server 3000', { background: true })

await sandbox.kill()
```

## Override environment variables for one command

Override or append environment variables for a single command with the `envs` option. It applies only to that command.

```python Python theme={null}
from ppio_sandbox import PPIO

ppio = PPIO()
sandbox = ppio.sandbox.create()

result = sandbox.commands.run(
    "echo $LOG_LEVEL",
    envs={"LOG_LEVEL": "info"},   # applies only to this command
)
print(result.stdout)   # info

sandbox.kill()
```

```javascript Node.js theme={null}
import { PPIO } from 'ppio-sandbox'

const ppio = new PPIO()
const sandbox = await ppio.sandbox.create()

const result = await sandbox.commands.run('echo $LOG_LEVEL', {
  envs: { LOG_LEVEL: 'info' }, // applies only to this command
})
console.log(result.stdout) // info

await sandbox.kill()
```

## Stream output as it is produced

For long-running commands, pass `on_stdout` / `on_stderr` in Python or `onStdout` / `onStderr` in Node.js to receive output as it is produced, instead of waiting for the command to finish. Each callback receives its output as soon as it exists, with stdout and stderr delivered separately. The returned result still contains the final exit code.

> [!WARNING]
>
> Keep callbacks lightweight. Long blocking work inside a callback holds up event processing and can disconnect the underlying connection. Buffer the data, or hand it to another task or thread, when heavy processing is needed.

```python Python theme={null}
from ppio_sandbox import PPIO

ppio = PPIO()
sandbox = ppio.sandbox.create()

result = sandbox.commands.run(
    'for i in 1 2 3; do echo line $i; sleep 1; done',
    on_stdout=lambda data: print('OUT:', data, end=''),
    on_stderr=lambda data: print('ERR:', data, end=''),
)
print('exit code:', result.exit_code)

sandbox.kill()
```

```javascript Node.js theme={null}
import { PPIO } from 'ppio-sandbox'

const ppio = new PPIO()
const sandbox = await ppio.sandbox.create()

const result = await sandbox.commands.run(
  'for i in 1 2 3; do echo line $i; sleep 1; done',
  {
    onStdout: (data) => {
      process.stdout.write(`OUT: ${data}`)
    },
    onStderr: (data) => {
      process.stderr.write(`ERR: ${data}`)
    },
  }
)

console.log('exit code:', result.exitCode)

await sandbox.kill()
```

### Stream a background command

To keep the program running while a command streams, start it with `background=True` in Python or `background: true` in Node.js. The call returns a `CommandHandle` instead of waiting for the result. The same callbacks can be attached, other work can continue, and `wait()` blocks until the command finishes and returns its `CommandResult`.

```python Python theme={null}
from ppio_sandbox import PPIO

ppio = PPIO()
sandbox = ppio.sandbox.create()

# Returns a CommandHandle immediately (does not wait)
handle = sandbox.commands.run(
    'for i in $(seq 1 5); do echo tick $i; sleep 1; done',
    background=True,
)

print('running as pid:', handle.pid)

# ... do other work while the command runs ...

# Stream logs and wait for completion; callbacks fire as output arrives
result = handle.wait(
    on_stdout=lambda data: print(data, end=''),
    on_stderr=lambda data: print(data, end=''),
)
print('exit code:', result.exit_code)

sandbox.kill()
```

```javascript Node.js theme={null}
import { PPIO } from 'ppio-sandbox'

const ppio = new PPIO()
const sandbox = await ppio.sandbox.create()

// Returns a CommandHandle immediately (does not wait)
const handle = await sandbox.commands.run(
  'for i in $(seq 1 5); do echo tick $i; sleep 1; done',
  {
    background: true,
    onStdout: (data) => {
      process.stdout.write(data)
    },
    onStderr: (data) => {
      process.stderr.write(data)
    },
  }
)

console.log('running as pid:', handle.pid)

// ... do other work while logs stream in the background ...

// Wait for completion and get the final result
const result = await handle.wait()
console.log('exit code:', result.exitCode)

await sandbox.kill()
```

## Retrieve the full output

When real-time output is not needed, run the command in the foreground and read the full `stdout` and `stderr` from the returned `CommandResult`. This is the simplest approach for commands with a predictable, short duration.

```python Python theme={null}
from ppio_sandbox import PPIO

ppio = PPIO()
sandbox = ppio.sandbox.create()

result = sandbox.commands.run('echo hello && echo oops 1>&2')

print('stdout:', result.stdout)
print('stderr:', result.stderr)
print('exit code:', result.exit_code)

sandbox.kill()
```

```javascript Node.js theme={null}
import { PPIO } from 'ppio-sandbox'

const ppio = new PPIO()
const sandbox = await ppio.sandbox.create()

const result = await sandbox.commands.run('echo hello && echo oops 1>&2')

console.log('stdout:', result.stdout)
console.log('stderr:', result.stderr)
console.log('exit code:', result.exitCode)

await sandbox.kill()
```

### Output of a background command

For a command started in the background, the accumulated output is also available on the handle after it completes.

```python Python theme={null}
from ppio_sandbox import PPIO

ppio = PPIO()
sandbox = ppio.sandbox.create()

handle = sandbox.commands.run('echo done', background=True)

result = handle.wait()

# Full output collected during execution
print(result.stdout)
print(result.stderr)

sandbox.kill()
```

```javascript Node.js theme={null}
import { PPIO } from 'ppio-sandbox'

const ppio = new PPIO()
const sandbox = await ppio.sandbox.create()

const handle = await sandbox.commands.run('echo done', { background: true })

const result = await handle.wait()

// Full output collected during execution
console.log(result.stdout)
console.log(result.stderr)

await sandbox.kill()
```

## Command options

> [tab] Python
>
> **cmd** `string`
>
> Command to execute.
>
> **background** `bool` (default: False)
>
> `True` returns a command handle and does not wait for the command to finish.
>
> **envs** `dict`
>
> Environment variables for this command only.
>
> **on\_stdout** `callable`
>
> Callback for stdout output as it is produced.
>
> **on\_stderr** `callable`
>
> Callback for stderr output as it is produced.

> [tab] Node.js
>
> **cmd** `string`
>
> Command to execute.
>
> **background** `boolean` (default: false)
>
> `true` returns a command handle and does not wait for the command to finish.
>
> **envs** `object`
>
> Environment variables for this command only.
>
> **onStdout** `function`
>
> Callback for stdout output as it is produced.
>
> **onStderr** `function`
>
> Callback for stderr output as it is produced.

## Result fields

> [tab] Python
>
> **stdout** `str`
>
> Full standard output collected from the command.
>
> **stderr** `str`
>
> Full standard error collected from the command.
>
> **exit\_code** `int`
>
> Command exit code. `0` indicates success.
>
> **error** `str`
>
> Error message when the command failed; otherwise empty.

> [tab] Node.js
>
> **stdout** `string`
>
> Full standard output collected from the command.
>
> **stderr** `string`
>
> Full standard error collected from the command.
>
> **exitCode** `number`
>
> Command exit code. `0` indicates success.
>
> **error** `string`
>
> Error message when the command failed; otherwise empty.

> [!NOTE]
>
> A command that exits with a non-zero code raises an error. The [Errors](https://docs.ppio.ai/sandbox/errors.md) page lists it, and the error carries the same `stdout`, `stderr`, `exitCode` and `error` fields, so the output is still readable after a failure.


## Related topics

- [Run a desktop sandbox for computer use](https://docs.ppio.ai/sandbox/computer-use.md)
- [Build a template with the SDK](https://docs.ppio.ai/sandbox/templates/build.md)
- [ppio sandbox exec](https://docs.ppio.ai/sandbox/cli/exec.md)


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