在python里调用java的py4j的使用方法

py4j可以使python和java互调

 

py4j并不会开启jvm,需要先启动jvm server,然后再使用python的client去连接jvm

 

 

 

GatewayServer实例:允许python程序通过本地网络socket来与JVM通信。

 

1、安装:pip install py4j

其中Python库会安装到Python目录,而Java库会安装到对应的目录,如/usr/local/share/py4j/py4j0.10.5.jar。​

2、启动Java虚拟机

要让Python代码调用JVM函数,需要先使用Py4J的Java库,启动一个JVM监听socket端口,代码如下,其中py4j.GatewayServer在前面安装得到的py4j0.10.5.jar包中。

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 is now the gateway.entry_point GatewayServer server = new GatewayServer(app);
  //GatewayServer server = new GatewayServer(app,25334); //使用其他端口 server.start(); //开始接收python请求 } }

 编译:

​javac -cp /usr/local/share/py4j/py4j0.10.5.jar  AdditionApplication.java

运行:默认会使用25333端口,可以lsof -i:25333进行查看

java -cp /usr/local/share/py4j/py4j0.10.5.jar:. AdditionApplication​

 

启动Python客户端

最后启动Python客户端就可以,通过Py4J提供的Python库,根据ip、port连接JVM启动的socket server,然后就可以使用Java实现的类了,而且类的属性和成员函数都可以dynamic使用。

>>> from py4j.java_gateway import JavaGateway

>>> gateway = JavaGateway()                   # connect to the JVM ,初始化一个JavaGateway,默认为localhost,端口25333

使用java自带的库 >>> random = gateway.jvm.java.util.Random() # create a java.util.Random instance >>> number1 = random.nextInt(10) # call the Random.nextInt method >>> number2 = random.nextInt(10) >>> print(number1,number2) (2, 7)
使用AdditionApplication服务的函数
>>> addition_app = gateway.entry_point # get the AdditionApplication instance >>> addition_app.addition(number1,number2) # call the addition method 9

如果要使用第三方的包,必须在运行时先包含进来,然后才可以使用:
引用第三方包my.jar,并使用里面的方法cn.huawei.tongdun.Add
java -cp /usr/local/share/py4j/py4j0.10.5.jar:/usr/local/my.jar:. AdditionApplication​
third_add = gateway.jvm.cn.huawei.tongdun.Add

 

刚开始,遇到找不到类的情况时,我想着把需要的jar包放入CLASSPATH下,但是失败告终

 

总结

Py4J​为Python调用JVM程序提供了很简易的接口,为Java/Scala应用提供Python API提供便利。Spark基于Py4J实现了PySpark也非常好用,在实际开发中除了启动GatewayServer,还需要处理多线程并发、SparkContext封装等工作。

类似Py4J,如果需要Python​调用C/C++后端,还可以使用swig,参考 TensorFlow 的实现。​​​​

 

参考:

1、https://weibo.com/ttarticle/p/show?id=2309404123715523750791&mod=zwenzhang

2、http://blog.csdn.net/u010159842/article/details/69251773

3、https://www.py4j.org/install.html#install-instructions

4、https://www.py4j.org/faq.html#how-to-import-a-class

posted @ 2018-02-08 10:54  脚本小娃子  阅读(8231)  评论(0编辑  收藏  举报