pythonjavafunctionparameters

Run Python function (with parameters) from Java


I'm making a java program that requires me to use python as well. What I want to do is get 3 values from the java code and then call a function from a python file with the 3 values as parameters. How do I go about this?

So far I've tried opening the file with simply:

File file = new File("python file location");
Desktop desktop = Desktop.getDesktop();
if(file.exists()) desktop.open(file);

and catching any IOException but this just runs the entire python file and not the specific function.


Solution

  • Are you trying to pass 3 values from the java program to the Python program, capture its output back to the java program? If so, then you are going about this way. The Desktop approach is really just to launch a new program, as you would do by clicking on an icon on a GUI desktop. (Fire and forget)

    If you want to take programmatic control of Python, then you need to use ProcessBuilder. (There is a older and lower level method you'll find documentation for Runtime.exec()).

    You'll want to write something like this:

    ProcessBuilder processBuilder = new ProcessBuilder("/path/program.py", "val1", "val2", "val3);
    Process process = processBuilder.start();
    

    Plenty of tutorials exist, e.g.: https://www.baeldung.com/java-lang-processbuilder-api

    It gets tricky reading the output of the program (process.getInputStream()), knowing how to parse the output from the program, when it has finished, etc and then stopping the invocation of the program.