【发布时间】:2014-04-18 15:30:43
【问题描述】:
我在 Python 中的 conda 虚拟环境中使用 pip 安装了 py4J。我写了一个超级简单的例子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)
更新 1
在我将:import py4j.GatewayServer; 添加到文件顶部后,我得到了一个不同的错误:
package py4j does not exist
更新 2
pip install py4j 在<PATH_TO_CONDA_ENVIRONMENT>/share/py4j/py4j0.8.1.jar 下留下了一个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
【问题讨论】:
-
我不明白。我完全按照您在这里所做的,但是当我运行:java -cp py4j0.10.8.1.jar AdditionApplication,我收到以下错误:“错误:无法找到或加载主类 AdditionApplication”。有什么想法吗?
-
对于 Mac/LInux: java -cp /usr/local/share/py4j/py4j0.10.5.jar :. AdditionApplication 对于 Windows:java -cp /usr/local/share/py4j/py4j0.10.5.jar AdditionApplication