How to call java method from python using py4j. I had a hard time with all the old Japanese documents, so I summarized them.
OS X Yosemite 10.10.5 anaconda 3.5.0(python 3.5.2)
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/
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.
https://www.py4j.org/ https://gist.github.com/bartdag/1070311
Recommended Posts