12

I would like to run a Process, and stream the process's stdout to the console. What is the best (most effective, easiest to understand, least lines of code) way to do this?

For example:

var process = await Process.start(exec, args);

I'd like to see any stdout contents as soon as they are available.

Thanks!

Seth Ladd
  • 112,095
  • 66
  • 196
  • 279

3 Answers3

16
import 'dart:io';
void main() async {
   var process = await Process.start(exec, args);
   process.stdout.pipe(stdout);
}

Or using then:

import 'dart:io';
void main() {
   Process.start(exec, args).then(
      (process) => process.stdout.pipe(stdout)
   );
}

https://api.dart.dev/dart-async/Stream/pipe.html

Zombo
  • 1
  • 62
  • 391
  • 407
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
4

Here's one way:

var process = await Process.start(exec, args);
stdout.addStream(process.stdout);

Notice that I add the process.stdout stream to the normal stdout stream, which comes from dart:io.

Seth Ladd
  • 112,095
  • 66
  • 196
  • 279
1

For completeness, you could use the mode argument in Process.start and pass a ProcessStartMode.inheritStdio

var process = await Process.start(
  command,
  args,
  mode: ProcessStartMode.inheritStdio
);

Be careful though, this will, as the mode's name implies, pass on all stdio from the process (stdin, stdout and stderr) to the default stdout which might cause unexpected results as stuff like sigterms are passed on too.

Erik W. Gren
  • 315
  • 2
  • 12