Skip to main content

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

Code Walkthrough

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:
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.

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!
==================================================