Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Source command not working through Java

From last day, I have been trying to execute a command on Terminal (MAC) using JAVA but whatever I do nothing is working.

I have the following 2 commands that I want to execute and get the output back in JAVA

source activate abc_env
python example.py

Till now, I have tried the following methods without any output

String[] command = new String[] { "source activate abc_env", "python example.py"};
String result = executeCommands(command);

Here is my executeCommands method

private static String executeCommands(String[] command) {

        StringBuffer output = new StringBuffer();

        Process p;
        try {
            for(int i=0; i< command.length;i++)
            {
                p = Runtime.getRuntime().exec(command[i]);
                p.waitFor();
                BufferedReader reader = 
                                new BufferedReader(new InputStreamReader(p.getInputStream()));

                String line = "";           
                while ((line = reader.readLine())!= null) {
                    output.append(line + "\n");
                }
                System.out.println("Error output: " + p.exitValue());
                System.out.println("Output:" + output);

            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("Here");
        }
        return output.toString();
    }

This gives me the following exception

Cannot run program "source": error=2, No such file or directory

I searched online and people say that source won't work like this and I should change the command to

String[] command = new String[] { "bash -c 'source activate abc_env'", "python example.py"};

Now, I donot get the exception but the command still does not work and it returns '2' as exitValue()

Then I tried to execute the commands as a script

#!/bin/bash
source activate abc_env
python example.py

I get the following exception when I read the .sh file as string and pass it to command

Cannot run program "#!/bin/bash": error=2, No such file or directory

So, my question is how to run the source command followed by python command properly through Java ? My final goal is execute some python from Java.

EDIT1: If I try the following command and print the output stream

String[] command = {
                "/bin/bash",
                "-c",
                "source activate cvxpy_env"
        };

executeCommand(command));

Output Stream:

ExitValue:1

ErrorOutput:/bin/bash: activate: No such file or directory

If I try the same command but with single quotes around 'source activate abc_env'. I get the following output

ExitValue:127

ErrorOutput:/bin/bash: source activate cvxpy_env: command not found

Solution:

String[] command = {
                "/bin/bash",
                "-c",
                "source /Users/pc_name/my_python_library/bin/activate abc_env;python example.py"
        };
like image 878
Behroz Sikander Avatar asked May 03 '15 09:05

Behroz Sikander


2 Answers

According to the Javadoc, Runtime.exec(String) breaks the command into the command-args list using a StringTokenizer, which will probably break your command into:

bash
-c
'source
activate
abc_env'

Which is obviously not what you want. What you should do is probably use the version of Runtime.exec(String[]) that accepts a ready list of arguments, passing to it new String[] {"bash", "-c", "source activate abc_env"}.

Now, to get an idea why it's not working, you should not only read from its stdout but also from stderr, using p.getErrorStream(). Just print out what you read, and it will be a great debugging aid.

Re: your edit. Now it looks like it's working fine, as far as Java and bash are concerned. The output "activate: No such file or directory" is probably the output from the successful run of the source command. It just that source can't find the activate file. Is it in the working directory? If not, you probably should have "cd /wherever/your/files/are; source activate cvxpy_env". Oh, and if your python script depends on whatever side-effects the source command has, you probably have to execute it in the same bash instance, that is:

String[] command = {
                "/bin/bash",
                "-c",
                "cd /wherever/your/files/are && source activate cvxpy_env && python example.py"
        };

Or better yet, pack it all into a single shell script, and then just Runtime.exec("./my_script.sh") (don't forget to chmod +x it, though).

like image 167
Sergei Tachenov Avatar answered Oct 23 '22 06:10

Sergei Tachenov


Try

String[] command = {
                "/bin/bash",
                "-c",
                "source activate abc_env; " + "python example.py"
        };
like image 30
Javide Avatar answered Oct 23 '22 06:10

Javide