简体   繁体   English

如何使用PY4J从python中调用java

[英]How to call java from python using PY4J

I want to call java from python with Py4J library, 我想用Py4J库从python中调用java,

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

I've got the following error: "Py4JNetworkError: An error occurred while trying to connect to the Java server". 我有以下错误:“Py4JNetworkError:尝试连接到Java服务器时出错”。 It's seems that no JVM is running, how to fix that? 似乎没有JVM在运行,如何解决?

Minimal working example: 最小的工作示例:

//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();
  }
}

Compile (make sure that the -cp path to the py4j is valid, otherwise adjust it such that it points to the right place): 编译(确保py4j的-cp路径有效,否则调整它使其指向正确的位置):

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

Run it: 运行:

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

Now, if you run your python script, in the terminal where the java AdditionApplication is running you should see something like: 现在,如果你运行你的python脚本,在运行java AdditionApplication的终端中你应该看到类似的东西:

>>> Hello World!

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();
      }
}

create a new class and run it(import py4j0.8.jar at 'py4j-0.8\\py4j-0.8\\py4j-java' first),then run python program 创建一个新类并运行它(首先在'py4j-0.8 \\ py4j-0.8 \\ py4j-java'中导入py4j0.8.jar),然后运行python程序

You should first start the java program, and then invoke java method from python. 首先应该启动java程序,然后从python中调用java方法。

py4j doesn't start jvm, it just connects to the already started java process. py4j没有启动jvm,它只是连接到已经启动的java进程。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM