# Streaming Output
<subtitle>Capture and process standard output and error streams in real-time during command execution to improve user interaction experience.</subtitle>

## Environment Setup

Before using the SDK, please ensure that the `AGENTBOX_API_KEY` environment variable is configured.

>
> You can obtain your API key from the [Console API Keys page](https://console.ucloud.cn/modelverse/experience/api-keys).

```bash
export AGENTBOX_API_KEY=your_api_key
```

For long-running commands or commands that need to show progress to users, you can receive data streams in real-time through callback functions without waiting for the entire command execution to end.

## Using Callback Functions

When calling `commands.run()`, pass `on_stdout` and `on_stderr` parameters.

```python
from ucloud_sandbox import Sandbox

sandbox = Sandbox.create()

# Define handler function
def handle_output(data):
    print(f"[LIVE]: {data.strip()}")

# Execute command and process results in real-time streaming
result = sandbox.commands.run(
    'for i in {1..5}; do echo "Step $i"; sleep 1; done',
    on_stdout=handle_output,
    on_stderr=handle_output
)
```

## Use Cases

*   **Progress Display**: Show real-time progress bars when executing installation scripts or complex calculations.
*   **Interactive Logging**: Forward real-time runtime logs from sandbox to frontend UI.
*   **Exception Monitoring**: Real-time scan for key error characters in `on_stderr` and immediately trigger alerts.

---

>
> **Performance Tip**: Callback functions are executed in separate listener threads. Please avoid performing time-consuming or blocking operations in callbacks to prevent affecting stream data reception.
