【问题标题】:Unable to get output from Apache Commons Exec无法从 Apache Commons Exec 获取输出
【发布时间】:2017-10-25 16:07:15
【问题描述】:

虽然标题非常相似,但这个问题不是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 命令

【问题讨论】:

    标签: java apache-commons-exec


    【解决方案1】:

    它在我的来自 IDEA 的 PC 上运行良好。尝试重新创建项目。添加有关您的环境的更多信息。 尝试将您的 python 代码放入 .py 文件并像“python test.py”一样运行它。

    【讨论】:

    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-11-12
      • 1970-01-01
      • 2012-11-05
      • 2018-10-28
      • 1970-01-01
      • 1970-01-01
      • 2011-11-09
      相关资源
      最近更新 更多