使用 Apache Commons Exec 时如何分别收集标准输出和标准错误?

How do I collect Standard Out and Standard Error separately when using Apache Commons Exec?

下面的代码获取所有输出,无论是 stdout 还是 stderr。

String line = String.format("paty/to/script.py");
CommandLine cmd = CommandLine.parse(line);
DefaultExecutor executor = new DefaultExecutor();
ByteArrayOutputStream stdout = new ByteArrayOutputStream();
PumpStreamHandler psh = new PumpStreamHandler(stdout);
executor.setStreamHandler(psh);
int exitvalue = executor.execute(cmd);
String output = stdout.toString();

如何分别获取两个流?

PumpStreamHandler 为 stderr 采用第二个构造函数参数。如您所见,只有一个 OutputStream 的构造函数将同时写入 stdout 和 stderr。
https://commons.apache.org/proper/commons-exec/apidocs/org/apache/commons/exec/PumpStreamHandler.html

所以下面的方法应该可以处理它。

    String line = String.format("paty/to/script.py");
    CommandLine cmd = CommandLine.parse(line);
    DefaultExecutor executor = new DefaultExecutor();
    ByteArrayOutputStream stdout = new ByteArrayOutputStream();
    ByteArrayOutputStream stderr = new ByteArrayOutputStream();
    PumpStreamHandler psh = new PumpStreamHandler(stdout, stderr);
    executor.setStreamHandler(psh);
    int exitvalue = executor.execute(cmd);
    String output = stdout.toString();
    String error = stderr.toString();