5

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"
        };
1
  • To make it even more clear, this "/Users/pc_name/my_python_library/bin/activate/" in linux could be translated to the path where Anaconda is installed, such as: "/opt/anaconda/bin/activate". Thus: source /opt/anaconda/bin/activate abc_env (if abc_env is your environment's name). Commented Jul 12, 2019 at 21:17

2 Answers 2

4

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).

Sign up to request clarification or add additional context in comments.

3 Comments

I tried the things you mentioned but I still have an error. I have updated my question. Kindly see EDIT1.
Ok great. I will try your new answer and will update u soon. Going for a meeting.
Great. I got it working. I just included the path of activate script and it worked fine. Thanks.
1

Try

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

4 Comments

See EDIT1. I tried the thing that you mentioned but still I have errors.
@Behroz You might need to specify the full path of your 'activate' and 'abc_env' scripts as well as 'example.py'. The error is telling you that it cannot find the file.
/bin/bash <---- this is what i get after whereis
String[] cmd = { "/bin/bash" , "-c", "cd /zookeeper/bin" + "./zkCli.sh"}; Runtime run = Runtime.getRuntime(); Process pr = run.exec(cmd); pr.waitFor(); BufferedReader buf = new BufferedReader(new InputStreamReader(pr.getInputStream())); String line = ""; while ((line=buf.readLine())!=null) { System.out.println(line); } whats wrong in this

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.