pub async fn stream_query<F>(
claude: &Claude,
cmd: &QueryCommand,
handler: F,
) -> Result<CommandOutput>where
F: FnMut(StreamEvent),Expand description
Execute a command with streaming output, calling a handler for each NDJSON line.
This spawns the claude process and reads stdout line-by-line, parsing each as a JSON event and passing it to the handler. Useful for progress tracking and real-time output processing.
Dropping the returned future mid-flight kills the spawned claude
process and, on Unix, its whole process group (SIGKILL): an
abandoned run does not keep executing in the background, and the
subprocesses it spawned for tool use die with it. Events already
dispatched to the handler are not rolled back.
ยงExample
use claude_wrapper::{Claude, QueryCommand, OutputFormat};
use claude_wrapper::streaming::{StreamEvent, stream_query};
let claude = Claude::builder().build()?;
let cmd = QueryCommand::new("explain quicksort")
.output_format(OutputFormat::StreamJson);
let output = stream_query(&claude, &cmd, |event: StreamEvent| {
if let Some(t) = event.event_type() {
println!("[{t}] {:?}", event.data);
}
}).await?;