尽管标题非常相似,但此问题并非Process output from apache-commons exec的重复项。
我正在尝试通过使用apache-commons exec获取命令的输出。这是我在做什么
import org.apache.commons.exec.*;
import java.io.ByteArrayOutputStream;
public class Sample {
private static void runCommand(String cmd) throws Exception {
ByteArrayOutputStream stdout = new ByteArrayOutputStream();
PumpStreamHandler psh = new PumpStreamHandler(stdout);
CommandLine cl = CommandLine.parse(cmd);
DefaultExecutor exec = new DefaultExecutor();
exec.setStreamHandler(psh);
exec.execute(cl);
System.out.println(stdout.toString());
}
public static void main(String... args) throws Exception {
String cmd1 = "python -c \"print(10)\"";
String cmd2 = "python -c \"import datetime; print(datetime.datetime.now())\"";
runCommand(cmd1); // prints 10
runCommand(cmd2); // should print the current datetime, but does not!
}
}
问题是
runCommand(cmd2)
不会在输出中输出任何内容。当我尝试在终端上运行命令时,它可以正常工作。我已经在有和没有IDE的情况下尝试了该程序,所以我确定这与IDE控制台无关。
这是截图
这是终端的屏幕截图
在终端上运行的Python命令
最佳答案
它在IDEA的我的PC上运行良好。尝试重新创建项目。添加有关您的环境的更多信息。
尝试将您的python代码放入.py文件,然后像“ python test.py”一样运行它。
关于java - 无法从Apache Commons Exec获取输出,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46937202/