我在Python的py4J
虚拟环境中使用pip安装了conda
。我写了一个超级简单的例子AdditionApplication.java
来测试py4J
,但它无法编译,即
javac AdditionApplication.java
无法抱怨GatewayServer
未定义。
我对Python很了解,但遗憾的是不是Java。我还需要提供什么?
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();
}
}
如果重要,我安装了以下版本的Java:
java -version
java version "1.7.0_51"
Java(TM) SE Runtime Environment (build 1.7.0_51-b13)
Java HotSpot(TM) 64-Bit Server VM (build 24.51-b03, mixed mode)
在我将import py4j.GatewayServer;
添加到文件顶部后,我收到了另一个错误:
package py4j does not exist
pip install py4j
在jar
下留下了<PATH_TO_CONDA_ENVIRONMENT>/share/py4j/py4j0.8.1.jar
个文件。我已将它添加到我的类路径中:
javac -cp <PATH_TO_CONDA_ENVIRONMENT>/share/py4j/py4j0.8.1.jar AdditionApplication.java
并输出
AdditionApplication.class
如何运行它?
应用之前的修补程序后,我最终运行代码:
java -cp <PATH_TO_CONDA_ENVIRONMENT>/share/py4j/py4j0.8.1.jar AdditionApplication
代码在后台运行。测试它:
>>> from py4j.java_gateway import JavaGateway
>>> gateway = JavaGateway() # connect to the JVM
>>> random = gateway.jvm.java.util.Random() # create a java.util.Random instance
>>> number1 = random.nextInt(10) # call the Random.nextInt method
>>> number2 = random.nextInt(10)
>>> print(number1,number2)
(2, 7)
>>> addition_app = gateway.entry_point # get the AdditionApplication instance
>>> addition_app.addition(number1,number2) # call the addition method
答案 0 :(得分:5)
从GatewayServer
包导入py4j
,以便可以在应用程序中使用非限定类
import py4j.GatewayServer;