javaapache-commons-exec

Unable to get output from Apache Commons Exec


Although the titles are very similar, this questions is NOT a duplicate of Process output from apache-commons exec.

I am trying to get the output of a command by using apache-commons exec. Here is what I am doing

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!
    }
}

The problem is that runCommand(cmd2) does not print anything to the output. When I try running the command on terminal, it works fine.

I have tried this program with and without the IDE so I'm sure this has nothing to do with the IDE console.

Here's a screenshot

enter image description here

Here's a screenshot of the terminal

enter image description here

Python command running on the terminal

enter image description here


Solution

  • A colleague was able to come up with a solution to this problem. Changing

    CommandLine cl = CommandLine.parse(cmd);
    

    to

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

    solved the issue.


    The complete code looks as follows:

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