如何设置Dart IO进程使用现有的流作为其stdin? [英] How do you set a Dart IO Process to use an existing Stream for its stdin?

查看:379
本文介绍了如何设置Dart IO进程使用现有的流作为其stdin?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Process.start创建一个进程,有点卡住了stdin getter。理想情况下,我有一个StreamController在其他地方设置,其流的字符串我想传递到stdin。但是有没有太多复杂的例子与Process.stdin进行交互,所以我不知道如何做任何事情比writeln到stdin。

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.

所以我've得到这样的东西,我可以添加String消息到:

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

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

我想这样做:

process(可执行文件,args,工作目录:dir.path,runInShell:true) .stdout
.transform(UTF8.decoder)
.listen((data){
s.add('[[CONSOLE_OUTPUT]]'+ data);
});
process.stdin.addStream(input.stream);
});

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); });

我意识到 addStream() code> Stream< List< int>> ,但我不知道为什么会这样。

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

推荐答案


stdin 对象是 IOSink ,因此它具有 write 方法为字符串。这将默认为UTF-8编码的字符串。
所以,而不是

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)

可以

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

你可能需要一些错误处理,可能会在写入之间刷新stdin,所以也许:

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);

或者,您可以手动进行UTF-8编码, code> addStream 期望:

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))

> stdin 期望 List< int> 是过程通信在其核心只是字节。发送文本需要发件人和接收者对编码进行预先约定,以便他们可以以相同的方式解释字节。

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.

这篇关于如何设置Dart IO进程使用现有的流作为其stdin?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆