Execute Python In Java

Introduction

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"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>SampleJpython</artifactId>
    <version>1.0-SNAPSHOT</version>

    <properties>
        <maven.compiler.source>11</maven.compiler.source>
        <maven.compiler.target>11</maven.compiler.target>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.python</groupId>
            <artifactId>jython-standalone</artifactId>
            <version>2.7.1</version>
        </dependency>
    </dependencies>

</project>

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");
        interpreter.execfile("src/main/java/testPython.py");
        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:

Summary

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


Similar Articles