How do I compile a standard error and a standard error when using Apache Commons Exec?

The following code gets all the output: stdout or 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();

How can I get both threads separately?

+4
source share
1 answer

PumpStreamHandleraccepts the second constructor argument for stderr. A constructor containing only one OutputStreamwill write to it both stdout and stderr, as you noticed. See https://commons.apache.org/proper/commons-exec/apidocs/org/apache/commons/exec/PumpStreamHandler.html

Therefore, this approach should be followed.

    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();
+5
source

Source: https://habr.com/ru/post/1622550/


All Articles