How to execute a Python tool installed in Python virtual environment from Java

Viewed 451

I want to run a Python tool installed in a python virtual environment from Java source code. What are the possible Java libraries that I can use for this purpose?

I have already tried below code: Runtime.getRuntime().exec("/Users/xxx/Documents/venv/bin/python3.7 yyy);

But this code doesn't work. It is to run a Python script (eg., yyy= script.py) from the virtual environment (venv). Therefore, it gives me an error saying there is no file called yyy. But my requirement is to run a Python tool installed in the virtual environment venv.

1 Answers

Your requirement might need a little clarification, but I suspect you can make it work with a ProcessBuilder. Use directory(File) to control the working directory for the command. And inheritIO() to make stdio work "automatically". Never hardcode a user's home folder. You can use System.getProperty(String) to retrieve the home folder.

ProcessBuilder pb = new ProcessBuilder();
pb.directory(new File(System.getProperty("user.home"), "Documents/venv/"));
pb.inheritIO();
try {
    Process p = pb.command("bin/python3.7",
            "lib/python3.7/site-packages/yyy").start();
    p.waitFor();
} catch (Exception e) {
    e.printStackTrace();
}

It might be better to use System.getenv(String) instead of relying on "Documents/venv" to contain the pyvenv root.

Related