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

# Stream Command

> Stream command output in real-time from a Declaw sandbox using Server-Sent Events.

## What You'll Learn

* Streaming command output with `sbx.commands.run_stream()` (Python) / `sbx.commands.runStream()` (TypeScript)
* Real-time `on_stdout` / `on_stderr` callbacks that fire as each line arrives
* Inspecting the final accumulated `CommandResult` after the stream completes
* Proper cleanup with `try/finally` and `sbx.kill()`

## Prerequisites

<Snippet file="snippets/env-setup.mdx" />

## Code Walkthrough

<Tabs>
  <Tab title="Python">
    Use `run_stream()` with `on_stdout` and `on_stderr` keyword callbacks. The call blocks until the command exits and returns a `CommandResult` with the full accumulated output:

    ```python theme={null}
    cmd = 'for i in 1 2 3 4 5; do echo "Processing step $i..."; sleep 0.5; done'

    result = sbx.commands.run_stream(
        cmd,
        on_stdout=lambda line: print(f"[STDOUT] {line}"),
        on_stderr=lambda line: print(f"[STDERR] {line}"),
    )

    print(f"stdout:\n{result.stdout}")
    print(f"stderr: {result.stderr!r}")
    print(f"exit_code: {result.exit_code}")
    ```

    Each line is delivered to `on_stdout` as it is emitted — no buffering until the command finishes. The returned `result.stdout` contains all lines joined together.
  </Tab>

  <Tab title="TypeScript">
    Use `runStream()` with `onStdout` and `onStderr` in the options object:

    ```typescript theme={null}
    const cmd =
      'for i in 1 2 3 4 5; do echo "Processing step $i..."; sleep 0.5; done';

    const result = await sbx.commands.runStream(cmd, {
      onStdout: (line: string) => console.log(`[STDOUT] ${line}`),
      onStderr: (line: string) => console.log(`[STDERR] ${line}`),
    });

    console.log(`stdout:\n${result.stdout}`);
    console.log(`stderr: ${JSON.stringify(result.stderr)}`);
    console.log(`exit_code: ${result.exitCode}`);
    ```

    The `await` resolves once the command exits. `result.stdout` holds the complete accumulated output.
  </Tab>
</Tabs>

## Expected Output

```
==================================================
Declaw Stream Command Example
==================================================

--- Creating Sandbox ---
Sandbox created: sbx_abc123

--- Streaming Command Output ---
[STDOUT] Processing step 1...
[STDOUT] Processing step 2...
[STDOUT] Processing step 3...
[STDOUT] Processing step 4...
[STDOUT] Processing step 5...

--- Final Result ---
stdout:
Processing step 1...
Processing step 2...
Processing step 3...
Processing step 4...
Processing step 5...
stderr: ''
exit_code: 0

--- Cleaning Up ---
Sandbox killed.

==================================================
Done!
==================================================
```
