Execute Python In Java


In the development teams of today's IT world, most of the time, developers will use multiple languages to develop an app. If they are using API development, then there will be no problem with integration. But, when we work with standalone applications, it can become difficult to integrate. In this case, the module like Jython plays the Superman role.

Below is the sample code of Python, which we need to execute with the Java compiler to be able to access the variables defined in Python.

filename: testPython.py

print("Test python")
x = 5 + 6
y = 6 - 5

Create a Java project. I used Maven to manage the dependencies mentioned in the pom.xml file.

For this, we need the package jython-standalone-2.7.1.jar.

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">





Below is the sample code for Java, which will read the testPython.py file and execute it to provide the output.

import org.python.util.PythonInterpreter;
public class Sample {
    public static void main(String[] args) {
        PythonInterpreter interpreter = new PythonInterpreter();
        System.out.println("Java runs python code using jython");
        System.out.println("x: " + interpreter.get("x"));
        System.out.println("x: " + interpreter.get("y"));

In the above code, we can see that the interpreter object will execute the file. With the help of the get method, we will be able to get the values of X and Y.

Below is the sample output:


In this article, we learned about the usage of jython, which will help us execute Java code in Python.