Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Java program can run python program with virtual environment?

Tags:

java

python

I had several python programs and all of them had each virtual environment.

I want to run these python programs in Java program.

Now I run python program in Java like below:

Process process = Runtime.getRuntime().exec(command)

but I don't know how to run with virtual enviroment.
Can Java program run each Python program with each virtual environment?

like image 651
BingbongKim Avatar asked Mar 26 '18 00:03

BingbongKim


People also ask

How do I run a Python program in virtual environment?

To use the virtual environment you created to run Python scripts, simply invoke Python from the command line in the context where you activated it. For instance, to run a script, just run python myscript.py .

Can you run a Python program from Java?

You can use Java Runtime. exec() to run python script, As an example first create a python script file using shebang and then set it executable.

Does Java have virtual environments?

A Java virtual machine (JVM) is a virtual machine that enables a computer to run Java programs as well as programs written in other languages that are also compiled to Java bytecode. The JVM is detailed by a specification that formally describes what is required in a JVM implementation.

Can you run Python on JVM?

The Jython project provides implementations of Python in Java, providing to Python the benefits of running on the JVM and access to classes written in Java. The current release (a Jython 2.7. x) only supports Python 2 (sorry).


1 Answers

In Runtime.exec(), ensure that the executable being executed is the python interpreter located inside the virtual environment.

For example, if your virtual environment is in /tmp/my-venv, use the following:

Process process = Runtime.getRuntime().exec("/tmp/my-venv/python hello.py");

Or:

Process process = Runtime.getRuntime().exec(new String[] {"/tmp/my-venv/python", "hello.py"});
like image 199
Isaac Avatar answered Oct 19 '22 15:10

Isaac