Call Python from Java

It is said that Python’s syntax is the best for engineers and such professionals, because it has a very steep learning curve, easy syntax and good documentation. These people have no time, interest or any reasons to learn a programming language like Java when they can breakdown a calculation and implement it in Python easily. But then it is software developer’s job to use those algorithms and formulas and implement them specific software. Here’s where Jython comes in handy, it allows to run Python from Java code. To do this, these are the requirements:

  • Python installed and added to PATH in system environment variables;
  • Jython installed;
  • Jython.jar (from Jython folder) added to build path of the said project;
  • Java installed (of course);
  • PyDev on Eclipse (to make Python coding easier).

First of all, we’re going to run an entire .py file from Java and we’re just going to print something in the console. Here’s the code:

JavaMain.java

package com.wordpress.breekmd.java;

import org.python.util.PythonInterpreter;

public class JavaMain {

	public static void main(String[] args) {
		PythonInterpreter interpreter = new PythonInterpreter();
		try {
			interpreter.execfile("D:/Projects workspace/JavaPythonMix/src/com/wordpress/breekmd/java/PythonMain.py");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

PythonMain.py

text = 'Hello. Test Succeeded!'
print text

This is what we see in the console:

Hello. Test Succeeded!

Ain’t that simple? Now let’s try and call only a specific method from the .py file, not the entire file. We’re going to modify the Java code a little and create a new .py file and add it to the /Jython/Lib folder. 

JavaMain.java

package com.wordpress.breekmd.java;

import org.python.core.PyObject;
import org.python.util.PythonInterpreter;

interface PyFunction{
	public void sumFunction(int a, int b);
}

public class JavaMain {

	public static void main(String[] args) {
		PythonInterpreter interpreter = new PythonInterpreter();
		try {
			interpreter.exec("from pyMain import sumOfNumbers");
			PyObject sumFunction = interpreter.get("sumOfNumbers");
			PyFunction function = (PyFunction) sumFunction.__tojava__(PyFunction.class);
			function.sumFunction(5, 10);
		} catch (Exception e) {
			e.printStackTrace();
			e.getMessage();
			e.toString();
		}
	}

}

pyMain.py

def printText(text):
    print(text)

def sumOfNumbers(a, b):
    print(a + b)

The console is just going to show us “15”, the sum of int “a” and int “b”.

One comment

  1. Very helpful thanks. I was wondering if you had any examples of Java calling a def out of a Python class? Thanks for any help.

Leave a comment