Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

The below code gets all of the output, whether 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 streams separately?

like image 256
Michael Avatar asked Jan 02 '16 22:01

Michael


1 Answers

PumpStreamHandler takes a second constructor argument for stderr. The constructor with only one OutputStream will have both stdout and stderr being written to it, as you observed.
See https://commons.apache.org/proper/commons-exec/apidocs/org/apache/commons/exec/PumpStreamHandler.html

So an approach as the following should handle it.

    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();
like image 199
h7r Avatar answered Nov 11 '22 23:11

h7r