How to call java from python using PY4J
Asked Answered
A

3

6

I want to call java from python with Py4J library,

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". It's seems that no JVM is running, how to fix that?

Ashe answered 24/12, 2013 at 2:36 Comment(1)
Don't you need a hostname and/or a port to connect to the REMOTE JVM?Velate
N
2
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

Nomology answered 24/12, 2013 at 6:12 Comment(0)
K
7

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):

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:

>>> Hello World!

Kalynkam answered 24/10, 2015 at 21:27 Comment(2)
I think you mean a ; not a : in your class path.Everyman
Depends on the platform you are using. : on UNIX or ; on Windows. A little bit more information on the topic can be found here.Kalynkam
N
2
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

Nomology answered 24/12, 2013 at 6:12 Comment(0)
C
-1

You should first start the java program, and then invoke java method from python.

py4j doesn't start jvm, it just connects to the already started java process.

Cartoon answered 24/12, 2013 at 4:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.