如何使用PY4J从python中调用java

我想用Py4J库从python中调用java,

from py4j.java_gateway import JavaGateway gateway = JavaGateway() # connect to the JVM gateway.jvm.java.lang.System.out.println('Hello World!') 

我有以下错误:“Py4JNetworkError:尝试连接到Java服务器时出错”。 似乎没有JVM正在运行,如何解决?

 package test.test; 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); server.start(); } } 

创建一个新类并运行它(首先在’py4j-0.8 \ py4j-0.8 \ py4j-java’导入py4j0.8.jar),然后运行python程序

最小的工作示例:

 //AdditionApplication.java import py4j.GatewayServer; public class AdditionApplication { public static void main(String[] args) { AdditionApplication app = new AdditionApplication(); // app is now the gateway.entry_point GatewayServer server = new GatewayServer(app); server.start(); } } 

编译(确保py4j的-cp路径有效,否则调整它使其指向正确的位置):

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

运行:

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

现在,如果你运行你的python脚本,在运行java AdditionApplication的终端中你应该看到类似的东西:

>>> Hello World!

您应该首先启动java程序,然后从python调用java方法。

py4j没有启动jvm,它只是连接到已经启动的java进程。