py4j——用python訪問java遇到的問題解決
阿新 • • 發佈:2019-01-31
簡單來說就是先裝上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
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();
}
}
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)