Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to stream stdout from a Process, in Dart?

Tags:

dart

dart-io

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!

like image 761
Seth Ladd Avatar asked Oct 21 '15 04:10

Seth Ladd


3 Answers

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

like image 188
Günter Zöchbauer Avatar answered Oct 21 '22 17:10

Günter Zöchbauer


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.

like image 40
Seth Ladd Avatar answered Oct 21 '22 18:10

Seth Ladd


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.

like image 45
Erik W. Development Avatar answered Oct 21 '22 18:10

Erik W. Development