下面的代码获取所有输出,无论是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();