0

I understand that to run another Java program from inside a Java program you use something like this:

Runtime.getRuntime().exec("/**A command goes here*/")

But how would I run a Python program that takes command-line arguments? More specifically, my Java program takes a file as a command-line argument. I then pass this file in to a Python program, which then produces another file in the same directory. I will be able to access this new file.

Can I simply call:

Runtime.getRuntime().exec("python /**directory_of_the_python_program arguments_for_program*/");

I'm also a bit confused about what goes inside "exec(...)".

1 Answer 1

2

Try capturing the standard output, so you can use print in python to output to this stream:

try {  
    Process p = Runtime.getRuntime().exec("python yourProgram.py thearg1 thearg2");  
    p.waitFor();
    InputStream stderr = proc.getOutputStream();
    InputStreamReader in = new InputStreamReader(stdout);
    BufferedReader reader = new BufferedReader(in);
    String line = null;
    while ((line = reader.readLine()) != null) {
        System.out.println("Python says: " + line);
    }
    int exitVal = proc.waitFor();
} catch (Exception e) {  
    e.printStackTrace();  
}

In your python program, to output to the Java program, use print like:

print 'Hi!'

To see what the Java program sent you, you can use sys.argv:

print 'The Java program sent me: ', str(sys.argv)

Note: I am not a python expert, and have not done much with it. Please tell me if I get some syntax wrong.

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

Comments

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.