Executing a Python Script From a Java File and Vise-Versa
Why Not Try When There Is A Way?
Hello everyone, greetings after a long time.
In this article, we are going to do something weird but can be helpful to some specific situations.
Yeah, we’re going to execute a Java file with a Python Script and also going to execute a Python Script with a Java Program.
First, let’s see how to execute a Java Program with Python Script.
Let’s create Java Program that has to be executed by the Python Script. (Let it be the simplest!)
When we compile and print the above code in CMD, we will receive the following output.

You can execute the same Java Program in Python as follows.
>>> import subprocess
>>> output = subprocess.check_output("java JavaFromPython", stderr=subprocess.PIPE)
And the output will be like
>>> print(output)
b’I am in Java Program\r\n’
Here,
b’
notation specifies a bytes string in Python.
Now, let’s see how to execute a Python Script with a Java Program.
We can do this in three different ways. Let’s see one by one.
- Runtime Class
In this method, we use the Python interpreter on our system with the exec method in the Runtime class. After that, we read the output from the Runtime class’s output stream and convert it to a Java int.
- ProcessBuilder Class
We utilize the ProcessBuilder class in the current Java versions because the Runtime class approach is a little outdated. This gives the arguments more structure.
- Jython
Java is supposed to be platform-agnostic, and calling a native application (like Python) isn’t exactly that.
There is a Java-based version of Python (Jython) that allows us to use Python in our Java apps. Because one of the most common challenges when using external libraries is getting them to compile and run successfully, we’ll walk through the process of creating and running a basic Java program with Jython.
To run this, download Jython Standalone from here, and paste it inside the following location.
C:\Program Files (x86)\Java\jdk1.8.0_65\jre\lib\ext
As a result, we can now use Python from Java in a platform-independent way. It’s a little slow, and it feels like the slowest of the three ways provided. Still, the fact that it’s a Python interpreter written in Java is really cool.
In all the cases, the output shall be 11.
Returned Value is : 11
Try to implement much more complicated codes and see how it works and share your experiences with me as well.
Hope this article can help. Share your thoughts too.