6

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?

Michael
  • 455
  • 7
  • 18

1 Answers1

5

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();
h7r
  • 4,944
  • 2
  • 28
  • 31