py4j——用python访问java遇到的问题解决

简单来说就是先装上py4j的包,然后在Python环境中去执行官网py4j的demo程序,但是遇到了一些问题。

ERROR:root:Exception while sending command.
Traceback (most recent call last):
  File "/opt/cloudera/parcels/CDH-5.10.0-1.cdh5.10.0.p0.41/lib/spark/python/lib/py4j-0.10.6-src.zip/py4j/java_gateway.py", line 908, in send_command
    response = connection.send_command(command)
  File "/opt/cloudera/parcels/CDH-5.10.0-1.cdh5.10.0.p0.41/lib/spark/python/lib/py4j-0.10.6-src.zip/py4j/java_gateway.py", line 1067, in send_command
    "Error while receiving", e, proto.ERROR_ON_RECEIVE)
Py4JNetworkError: Error while receiving
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/opt/cloudera/parcels/CDH-5.10.0-1.cdh5.10.0.p0.41/lib/spark/python/lib/py4j-0.10.6-src.zip/py4j/java_gateway.py", line 1160, in __call__
  File "/opt/cloudera/parcels/CDH-5.10.0-1.cdh5.10.0.p0.41/lib/spark/python/lib/py4j-0.10.6-src.zip/py4j/protocol.py", line 328, in get_return_value
py4j.protocol.Py4JError: An error occurred while calling o0.nextInt

后来找了stackoverflow上的一个答案py4j.protocol.Py4JNetworkError : An error occurred while trying to connect to the Java server知道了该怎么解决,需要单独开启JavaGateway,这里运用java的一个程序去开启。

import py4j.GatewayServer;

public class myTest {

    public static void main(String[] args) {
        myTest app = new myTest();
        // app is now the gateway.entry_point
        GatewayServer server = new GatewayServer(app);
        server.start();
    }
}

但是又遇到了一个问题,
myTest.java:1: error: package py4j does not exist
是因为py4j的jar包没有引入,于是在集群的目录下找到了这个包,不过某个博客说对于linux系统,作为系统级的库,就会在/usr/share/py4j/py4j0.x.jar;而对于windows么就在C:\python27\share\py4j\py4j0.x.jar,这个得看个人情况去找了。
于是我就将java程序与这个jar包放到一个目录下执行

javac -classpath ./py4j0.9.jar myTest.java

生成.class文件后
java -classpath .:./py4j0.9.jar myTest
便启动了JavaGateway
最后在Python的环境下执行

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

猜你喜欢

转载自blog.csdn.net/u013488563/article/details/76855174