py4j可使python和java互调html
py4j并不会开启jvm,须要先启动jvm server,而后再使用python的client去链接jvmjava
GatewayServer实例:容许python程序经过本地网络socket来与JVM通讯。python
一、安装:pip install py4jgit
其中Python库会安装到Python目录,而Java库会安装到对应的目录,如/usr/local/share/py4j/py4j0.10.5.jar。github
要让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客户端就能够,经过Py4J提供的Python库,根据ip、port链接JVM启动的socket server,而后就可使用Java实现的类了,并且类的属性和成员函数均可以dynamic使用。app
>>> 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 的实现。
参考:
一、https://weibo.com/ttarticle/p/show?id=2309404123715523750791&mod=zwenzhang
二、http://blog.csdn.net/u010159842/article/details/69251773
三、https://www.py4j.org/install.html#install-instructions
四、https://www.py4j.org/faq.html#how-to-import-a-class