无法从 Apache Commons Exec 获取输出

Unable to get output from Apache Commons Exec

尽管标题非常相似,但此问题不是 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".

一位同事想出了解决这个问题的办法。改变

CommandLine cl = CommandLine.parse(cmd);

CommandLine cl = new CommandLine("/bin/sh");
cl.addArguments("-c");
cl.addArguments("'" + cmd + "'", false);

解决了问题。


完整代码如下:

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);
        CommandLine cl = new CommandLine("/bin/sh");
        cl.addArguments("-c");
        cl.addArguments("'" + cmd + "'", false);

        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);
    }
}