我正在Dart中启动一个将其stdout流附加到stdout的过程,以便可以将结果打印到终端,如下所示:
Process.start(executable, ['list','of','args']).then((proc) {
stdout.addStream(proc.stdout);
stderr.addStream(proc.stderr);
return proc.exitCode;
});
但是,一旦完成,我想开始一个新的过程,然后再次开始(此函数将被多次调用)。有时,我遇到一个错误:
Uncaught Error: Bad State: StreamSink is already bound to a stream
查看dart文档,看来我可能需要做类似
stdout.close()
或stdout.flush()
的操作,但是这些似乎并不能解决问题。处理具有顺序绑定(bind)到流接收器的多个流的正确方法是什么? 最佳答案
addStream
返回一个Future,它指示何时添加流。只能将一个addStream
的流同时发送到StreamSink
。
根据您想要/需要做的事情,现在有两种选择:
addStream
完成。 后者更容易:
Process.start(executable, ['list','of','args']).then((proc) async {
await stdout.addStream(proc.stdout); // Edit: don't do this.
await stdout.addStream(proc.stderr);
return proc.exitCode;
});
注意主体上的
async
修饰符,主体上的两个await
。编辑:不立即听stderr是一个错误。 (您的程序可能会阻止它)。
如果程序的输出足够小,则可以切换到
Process.run
:Process.run(executable, ['list','of','args']).then((procResult) {
stdout.write(procResult.stdout);
stdout.write(procResult.stderr);
return procResult.exitCode;
});
但是,它不会交错stdout和stderr。