Fitting Java and Python with JPY

There are many libraries in Java (more than 176,649 unique artifacts indexed just on Maven Central), but sometimes you can not find what you are looking for, except for a Python equivalent. In a previous project, I had to deal with custom MaxMind databases. Maxmind provides a Java library with a database reader, but does not provides a database writer. After some researches, I found one official lib in Perl, and an other (unofficial) in Python. Since, I didn’t have the time to redevelop the equivalent in Java (this was just a POC…), I’ve decided to use a bridge on one of these two libraries. I didn’t find any easy and production-ready solution to call some Perl in Java (exposing the library as a remote service, create a native process from Java and play with the shell,…) so I tried the unofficial project in Python because some bridges can fit Python and Java together.

In this post I will explain how to use a Python project or library in your Java projects by using JPY. JPY is a bi-directional Python-Java bridge which you can use to embed or call Python code in Java programs or vice versa. JPY is a Python module written in C and compiled into a shared library used by the Python JPY and by the JPY Java library as a native library.

JPY is not deployed on the central Maven repositories, so you have to clone it and compile it on your Linux/Mac or Windows. After the setup, you should see these files into your JPY project:

tree ~/git/jpy
├── build
│   ├── bdist.linux-x86_64
│   ├── lib.linux-x86_64-2.7
│   │   ├──
│   │   ├──
│   │   ├──
│   │   ├── jpyconfig.pyc
│   │   ├──
│   │   ├──
│   │   └── jpyutil.pyc
├── dist
│   └── jpy-0.9_SNAPSHOT-cp27-cp27mu-linux_x86_64.whl
├── target
│   └── jpy-0.9-SNAPSHOT.jar

Now you can use the freshly compiled JAR in your project. Create a new project with a layout like this:

├── pom.xml
├── requirements.txt
├── src
│   ├── main
│   │   ├── assembly
│   │   │   ├──
│   │   │   └── zip.xml
│   │   ├── java
│   │   │   └── fr
│   │   │       └── layer4
│   │   │           └── jpy
│   │   │               ├──
│   │   │               ├──
│   │   │               └──
│   │   ├── python
│   │   │   └──
│   │   └── resources
│   │       └──

Some explanations:
– the class is the Java class calling our Python scripts.
– is a module inside the project.
– requirements.txt contains all the Python dependencies. It will contain only “requests==2.11.1” for our example.
– we use the exec-maven-plugin to fetch the dependencies in the requirements.txt file via a “pip install”.
– all the dependencies are zipped with a blank file “” in the root, into an archive named
– this archive is embed in the final jar.
– a file must be provided in the classpath and defined the mandatory properties for JPY. After having built the JPY project, you can find this file in the build/lib.linux-x86_64-2.7 directory. Mine is:

# Created by '' tool on 2017-02-13 15:37:50.987325
# This file is read by the jpy Java API (org.jpy.PyLib class) in order to find shared libraries
jpy.jpyLib = /home/devil/git/jpy/build/lib.linux-x86_64-2.7/
jpy.jdlLib = /home/devil/git/jpy/build/lib.linux-x86_64-2.7/
jpy.pythonLib = /usr/lib/x86_64-linux-gnu/
jpy.pythonPrefix = /usr
jpy.pythonExecutable = /usr/bin/python

Since the JPY libs depend on the architecture (Linux, Windows, x86…) of the target host, this file should be deployed on every hosts on which you plan to install your application and never be included in the final archive of your project. is really simple, it defines two methods, one using the Python requests module:

import requests

class MyPlugin:
    def process(self, arg):
        return arg.split();
    def curl(self, url):
        return requests.get(url);

In, we can find the same methods:

public interface MyPlugin {
    String[] process(String arg);
    PyObject curl(String url);

Now here is the magic:

package fr.layer4.jpy;

import org.jpy.PyInputMode;
import org.jpy.PyLib;
import org.jpy.PyModule;
import org.jpy.PyObject;
import org.springframework.util.FileSystemUtils;
import org.springframework.util.ResourceUtils;
import org.springframework.util.StringUtils;

import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;

public class Main {

    public static void main(String... args) throws Exception {


        // Prepare required system properties like 'jpy.jpyLib' and others
        Properties properties = new Properties();
        properties.load(new FileInputStream(ResourceUtils.getFile("")));
        properties.forEach((k, v) -> System.setProperty((String) k, (String) v));

        if (!PyLib.isPythonRunning()) {
            List<String> extraPaths = Arrays.asList(
                    "", // REQUIRED: contains all the dependencies
                    "" // OPTIONAL: my custom scripts
            List<String> cleanedExtraPaths = new ArrayList<>(extraPaths.size());

            Path tempDirectory = Files.createTempDirectory("lib-");
            Runtime.getRuntime().addShutdownHook(new Thread(() -> FileSystemUtils.deleteRecursively(tempDirectory.toFile())));

            extraPaths.forEach(lib -> {
                if (lib.startsWith("classpath:")) {
                    try {
                        String finalLib = lib.replace("classpath:", "");
                        Path target = Paths.get(tempDirectory.toString(), finalLib);
                        try (InputStream stream = Main.class.getClassLoader().getResourceAsStream(finalLib)) {
                            Files.copy(stream, target, StandardCopyOption.REPLACE_EXISTING);
                        if (finalLib.endsWith(".zip")) {
                            ZipUtils.extract(target.toFile(), tempDirectory.toFile());
                    } catch (Exception e) {
                } else {

            PyLib.startPython(cleanedExtraPaths.toArray(new String[]{}));

        try {
            // Exec a python script
            PyObject.executeCode("print 'this is from python'", PyInputMode.SCRIPT);

            // Proxify the call to a python class
            PyModule plugInModule = PyModule.importModule("my_plugin");
            PyObject plugInObj ="MyPlugin");
            MyPlugin plugIn = plugInObj.createProxy(MyPlugin.class);

            String[] results = plugIn.process("AAA bbb c ddd");

            PyObject response = plugIn.curl("");
            System.err.println(response.getAttribute("status_code").getIntValue()); // r.status_code
            System.err.println(response.getAttribute("text").getStringValue()); // r.text
            System.err.println("json").call("get", "login").getStringValue()); // r.json['login']
            System.err.println(response.getAttribute("headers").call("get", "content-type").getStringValue()); // r.headers['content-type']
        } finally {

Many lines of code, I agree. All this configuration, just for this:

PyModule plugInModule = PyModule.importModule("my_plugin");
PyObject plugInObj ="MyPlugin");
MyPlugin plugIn = plugInObj.createProxy(MyPlugin.class);

With JPY you can “implement” Java interfaces using Python by proxifying a Java interface with Python modules or classes. If you call methods of the resulting Java object, jpy will delegate the calls to the matching Python module functions or class methods.

Package the whole project as a fat-jar, run it, and you should see these outputs in the console:

> java -cp target/jpy-test-1.0-SNAPSHOT.jar:/home/devil/git/jpy/build/lib.linux-x86_64-2.7 fr.layer4.jpy.Main

this is from python
{"login":"Treydone","id":1038029,"avatar_url":"","gravatar_id":"","url":"","html_url":"","followers_url":"","following_url":"{/other_user}","gists_url":"{/gist_id}","starred_url":"{/owner}{/repo}","subscriptions_url":"","organizations_url":"","repos_url":"","events_url":"{/privacy}","received_events_url":"","type":"User","site_admin":false,"name":"Vincent Devillers","company":"Layer4","blog":"","location":"Paris","email":null,"hireable":true,"bio":null,"public_repos":26,"public_gists":9,"followers":23,"following":22,"created_at":"2011-09-09T08:13:08Z","updated_at":"2017-02-01T08:40:52Z"}
application/json; charset=utf-8


Here is the pom.xml used for this project:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns=""







All the sources can be found on Github


“Snake on Grey Wood” by Pixabay is licensed under CC0 1.0 / Resized

Related Posts

Leave a comment