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

# Stream Command Output

> Read stdout and stderr while a command is still running

A foreground command can deliver output as it is produced. Pass a callback, or iterate the events. The call finishes when the command exits.

```python Python theme={"dark"}
from gravixlayer import GravixLayer

client = GravixLayer()
sandbox = client.runtime.create()

result = sandbox.run_cmd(
    command="sh -lc 'echo hello; sleep 1; echo world'",
    on_stdout=lambda chunk: print(chunk, end="", flush=True),
    on_stderr=lambda chunk: print(chunk, end="", flush=True),
)
print(result.exit_code)

for event in sandbox.stream_cmd(command="sh -lc 'echo one; echo two'"):
    if event["type"] == "stdout":
        print(event["data"], end="", flush=True)
    elif event["type"] == "end":
        print(event["exit_code"])

sandbox.kill()
```

```typescript TypeScript theme={"dark"}
import { GravixLayer } from 'gravixlayer';

const client = new GravixLayer();
const sandbox = await client.runtime.create();

const result = await sandbox.runCmd("sh -lc 'echo hello; sleep 1; echo world'", {
  onStdout: (chunk) => process.stdout.write(chunk),
  onStderr: (chunk) => process.stderr.write(chunk),
});
console.log(result.exitCode);

for await (const event of sandbox.streamCmd("sh -lc 'echo one; echo two'")) {
  if (event.type === 'stdout') process.stdout.write(event.data);
  if (event.type === 'end') console.log(event.exitCode);
}

await sandbox.kill();
```

```bash CLI theme={"dark"}
gravixlayer runtime exec "$RT" --stream -- sh -lc 'echo hello; sleep 1; echo world'
```

```bash cURL theme={"dark"}
curl -N -X POST "https://api.gravixlayer.ai/v1/agents/runtime/$RT/commands/run?stream=true" \
  -H "Authorization: Bearer $GRAVIXLAYER_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{"command":"sh","args":["-lc","echo hello; sleep 1; echo world"]}'
```

Each event is one JSON object. `stdout` and `stderr` carry `data`. `end` carries `exit_code` and `timed_out`. `ping` is a keepalive. A stream always finishes with `end` or `error`.

Closing this stream stops the command. A non-zero exit is the command's result, not an API error.


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