How do you set a Dart IO Process to use an existing Stream for its stdin?

岁酱吖の 提交于 2019-12-11 04:52:14

问题


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.


回答1:


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.




回答2:


This might work

process.stdin.addStream(UTF8.encoder.bind(input.stream));


来源:https://stackoverflow.com/questions/28035515/how-do-you-set-a-dart-io-process-to-use-an-existing-stream-for-its-stdin

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!