无法从 py4j 中的 Python 启动网关

Unable to launch gateway from Python in py4j

我正在尝试使用 py4j 从 Python 端发射 JavaGateway。这是重现我遇到的问题所需的最少文件。

py4j.Py4JException: Target Object ID does not exist for this gateway :t

A.java

public class A {
}

EntryPoint.java

import py4j.GatewayServer;

public class EntryPoint {
    public A getA() {
        return new A();
    }

    public static void main(String[] args) {
        GatewayServer gatewayServer = new GatewayServer(new EntryPoint());
        gatewayServer.start();
        System.out.println("server started");
    }
}

我使用 IntelliJ 构建 .jar 文件,其中主要 class 是 EntryPoint 并且 py4j.jar 作为依赖项包含在内。

现在,我尝试通过引用 python 中生成的 .jar 文件的路径来启动网关。

test.py

from py4j.java_gateway import JavaGateway

gateway = JavaGateway.launch_gateway(classpath = '../out/artifacts/debugPy4j_jar/debugPy4j.jar')

a = gateway.entry_point.getA()

如有任何解决此问题的建议,我们将不胜感激。

您不能用 launch_gateway 指定自定义 Main class,这意味着您不能指定入口点。您只能指定一个 classpath,它附加到 Py4J jar 文件的路径。

"t"是Java这边入口点的名称:因为没有入口点,Py4J找不到对象"t"。这个实现细节应该不会在面向用户的异常中泄露。

launch_gateway 被硬编码为使用 py4j.GatewayServer 作为主 class 因为它期望 Java 端以某种方式表现。

在您的情况下,您仍然可以在 GatewayServer 启动后从 Python 创建一个 EntryPoint 实例:

from py4j.java_gateway import JavaGateway

gateway = JavaGateway.launch_gateway(classpath='../out/artifacts/debugPy4j_jar/debugPy4j.jar')

a = gateway.jvm.A()