问题描述
我有一个相当冗长的命令行程序,需要用户输入参数,然后使用这些参数进行处理。我想做的是将程序分为交互式和非交互式。我试图这样做,并打算让非交互式程序调用交互式程序并使用结果(参数),基于这些参数的过程。程序的非交互部分在处理时在控制台上显示结果。我看过Process.run和Process.start,但显然他们不以这种方式工作。还有另一个类似的问题,大约12个月大,所以我认为它值得再次询问。
I have a fairly lengthy command-line program that requires user input of parameters and then processes using those parameters. What I would like to do is split the program into interactive and non-interactive. I attempted to do that, and intended to have the non-interactive program "call" the interactive program and using the results (parameters), process based on those parameters. The non-interactive part of the program displays results on the console as it processes. I have looked at Process.run and Process.start, but apparently they don't function that way. There is another similar question to this that is about 12-months old, so I thought it worthwhile asking again.
推荐答案
Process.start
它可以做你想要的,但你必须成为一个更舒适的异步编程,如果你还没有。
Process.start
is what you want here. It can do what you want, but you'll have to become a bit more comfortable with async programming if you aren't already. You'll spawn the process and then asynchronously read and write to the spawned processes stdout and stdin streams.
您的交互式程序可以执行这样的操作:
Your interactive program can do something like this:
// interactive.dart
import 'dart:io';
main() {
var input = stdin.readLineSync();
print(input.toUpperCase());
}
使用 stdin
从命令行读取输入。然后,它使用常规 print()
输出处理结果。
It's using stdin
to read input from the command line. Then it outputs the processed result using regular print()
.
非交互式脚本可以生成并驱动使用类似:
The non-interactive script can spawn and drive that using something like:
import 'dart:convert';
import 'dart:io';
main() {
Process.start("dart", ["interactive.dart"]).then((process) {
process.stdin.writeln("this is the input");
UTF8.decoder.fuse(new LineSplitter()).bind(process.stdout).listen((line) {
print(line);
});
});
}
它使用 Process.start
生成交互式脚本。它使用 process.stdin
写入它。要读取生成的输出,它必须跳过一些箍将原始字节输出转换为每行的字符串,但这是基本的想法。
It uses Process.start
to spawn the interactive script. It writes to it using process.stdin
. To read the resulting output it has to jump through some hoops to convert the raw byte output to strings for each line, but this is the basic idea.
这篇关于从另一个Dart程序运行交互式Dart程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!