How to call java from python using PY4J

I want to call java from python with the Py4J library,

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

I got the following error: "Py4JNetworkError: An error occurred while trying to connect to the Java server." The JVM does not seem to work, how to fix it?

+4
source share
3 answers
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 (first import py4j0.8.jar into 'py4j-0.8 \ py4j-0.8 \ py4j-java'), then run the python program

+1
source

Minimum 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 path -cpto py4j is valid, otherwise configure it so that it points to the right place):

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

Run it:

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

, python script, , java AdditionApplication, - :

>>> Hello World!

+4

You must first run the java program and then call the java method from python.

py4j does not start jvm, it just connects to an already running Java process.

0
source

All Articles