An easy way to call Java from Python

Introduction

How to call java method from python using py4j. I had a hard time with all the old Japanese documents, so I summarized them.

environment

OS X Yosemite 10.10.5 anaconda 3.5.0(python 3.5.2)

Installation

After installing py4j with pip, copy the jar so that Java can read py4j.

$ pip install py4j
$ sudo cp ~/.pyenv/versions/(Virtual environment name)/share/py4j/py4j(version).jar /Library/Java/Extensions/

Implementation

As in the official tutorial, let's create a simple sample of addition in Java. First, create the following Java program.

AdditionApplication.java


import py4j.GatewayServer;

public class AdditionApplication {

  public int addition(int first, int second) {
    return first + second;
  }

  public static void main(String[] args) {
    AdditionApplication app = new AdditionApplication();
    //app gateway.entry_Set to point
    GatewayServer server = new GatewayServer(app);
    server.start();
    System.out.println("Gateway Server Started")
  }
}

After creating it, start the server with the following command.

$ javac AdditionApplication.java
$ java AdditionApplication

Next, let's write a python program to call AdditionApplication.

from py4j.java_gateway import JavaGateway

#Connect to JVM
gateway = JavaGateway() 
# java.util.Create a Random instance
random = gateway.jvm.java.util.Random()   
# Random.Call nextInt
number1 = random.nextInt(10)              
number2 = random.nextInt(10)
print(number1,number2) # (2, 7)
#Get an instance of AdditionApplication
addition_app = gateway.entry_point        
#Call addition
sum_num=addition_app.addition(number1,number2)    
print(sum_num) # 9

For the time being, it can be called from python. However, it is a little troublesome to start and stop the server from the terminal. Anyway, let's run it in python from start to finish.

#Execute by specifying the classpath
args=(["java","-cp",'/path/to/class/','AdditionApplication'])
p=subprocess.Popen(args)
#Prevent processing from going down before starting the server
time.sleep(3) 
gateway = JavaGateway(start_callback_server=True)
random = gateway.jvm.java.util.Random()
n1 = random.nextInt(10)
n2 = random.nextInt(10)
print(number1,number2) # (2, 7)
addition_app = gateway.entry_point
print(addition_app.addition(n1, n2)) # 9
#Kill the process
gateway.shutdown()

You can now run it consistently with python until the end. It can be used when inheriting a project of a Javer person, when there is a Java library you want to use, or when you want to implement some processing that requires speed in Java.

reference

https://www.py4j.org/ https://gist.github.com/bartdag/1070311

Recommended Posts

An easy way to call Java from Python
Call Matlab from Python to optimize
Easy way to customize Python import
[Python Tutorial] An Easy Introduction to Python
[Python] An easy way to visualize energy data interactively [plotly.express]
Easy way to use Wikipedia in Python
An easy way to hit the Amazon Product API in Python
Easy way to use Python 2.7 on Cent OS 6
Changes from Python 3.0 to Python 3.5
Changes from Python 2 to Python 3.0
From easy git installation to docker startup python
Easy way to check the source of Python modules
Easy way to scrape with python using Google Colab
[Python] How to call a c function from python (ctypes)
Call CPLEX from Python (DO cplex)
Post from Python to Slack
Anaconda updated from 4.2.0 to 4.3.0 (python3.5 updated to python3.6)
[Python] Another way to import
Connect to sqlite from python
Easy way to rename files
An introduction to Python Programming
An easy way to pad the number with zeros depending on the number of digits [Python]
Call C language functions from Python to exchange multidimensional arrays
Go language to see and remember Part 8 Call GO language from Python
PyArmor ~ Easy way to encrypt and deliver python source code ~
How to call Python or Julia from Ruby (experimental implementation)
An easy way to view the time taken in Python and a smarter way to improve it
Call a Python function from p5.js.
Call C from Python with DragonFFI
Create folders from '01' to '12' with python
Post from python to facebook timeline
Operate an I2C-connected display from Python
[Lambda] [Python] Post to Twitter from Lambda!
Call popcount from Ruby / Python / C #
Python (from first time to execution)
Post images from Python to Tumblr
Call python from nim with Nimpy
Python to switch from another language
Easy Python to learn while writing
An introduction to Python for non-engineers
An alternative to `pause` in Python
Call Java class from CPython (Py4J)
Call C / C ++ from Python on Mac
Call c language from python (python.h)
Did not change from Python 2 to 3
Update Python on Mac from 2 to 3
Easy way to round off to the nearest whole number with python3
Try to extract a character string from an image with Python3
An easy way to re-execute a previously executed command in ipython
Simple code to call a python program from Javascript on EC2
Call dlm from python to run a time-varying coefficient regression model
How to display bytes in the same way in Java and Python
Why I moved from Java to Dart
C language to see and remember Part 2 Call C language from Python (argument) string
[Note] [PyTorch] From installation to easy usage
python3 How to install an external module
How to update Google Sheets from Python
How to convert Python to an exe file
Send a message from Python to Slack
Private Python handbook (updated from time to time)
I want to use jar from python