Wednesday, October 8, 2014

Jython - Calling Python from Java

Let's say you do most of your development in Java, however, there is some existing Python code you need to reuse. In this post, I'll show you how to use Jython to call Python from Java.

Write a Java wrapper class:
public class JythonDemo {

    public int testMe(int num1, int num2) {
        PythonInterpreter python = new PythonInterpreter();

        python.set("num1", num1);
        python.set("num2", num2);
        python.exec("num3 = num1 + num2");
        PyObject num3 = python.get("num3");

        return Integer.parseInt(num3.toString());

    }
}

If using Maven, here is your pom.xml:
<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>com.noushin</groupId>
    <artifactId>demo</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>war</packaging>
    <name>demo</name>
    <description>Demo</description>

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

</project>
Just call testMe(), and that'll run your Python code:
JythonDemo jythonDemo = new JythonDemo();
int result = jythonDemo.testMe();


No comments:

Post a Comment