How do you set a Dart IO Process to use an existin

2019-08-03 15:30发布

I'm creating a Process using Process.start and am a bit stuck with the stdin getter. Ideally, I've got a StreamController set up elsewhere, whose stream of Strings I'd like to pass into stdin. But there aren't too many sophisticated examples for interacting with Process.stdin, so I'm not sure how to do anything more than a writeln to stdin.

So I've got something like this, that I can add String messages to:

  StreamController<String> processInput = new StreamController<String>.broadcast();

And I want to do something like this:

  Process.start(executable, args, workingDirectory: dir.path, runInShell: true).then((Process process) {
process.stdout
  .transform(UTF8.decoder)
  .listen((data) {
    s.add('[[CONSOLE_OUTPUT]]' + data);
  });
process.stdin.addStream(input.stream);
});

I realize that addStream() wants Stream<List<int>>, though I'm not sure why that's the case.

标签: dart dart-io
2条回答
淡お忘
2楼-- · 2019-08-03 15:49

This might work

process.stdin.addStream(UTF8.encoder.bind(input.stream));
查看更多
成全新的幸福
3楼-- · 2019-08-03 16:12

The stdin object is an IOSink, so it has a write method for strings. That will default to UTF-8 encoding the string. So, instead of

process.stdin.addStream(input.stream)

you can do

IOSink stdin = process.stdin;
input.stream.listen(stdin.write, onDone: stdin.close);

You may want some error handling, possibly flushing stdin between writes, so maybe:

input.stream.listen(
    (String data) {
      stdin.write(data);
      stdin.flush();
    }, 
    onError: myErrorHandler,
    onDone: stdin.close);

Alternatively you can do the UTF-8 encoding manually, to get the stream of list of integers that addStream expects:

process.stdin.addStream(input.stream.transform(UTF8.encoder))

The reason why stdin expects a List<int> is that process communication is, at its core, just bytes. Sending text requires the sender and the receiver to pre-agree on an encoding, so they can interpret the bytes the same way.

查看更多
登录 后发表回答