現(xiàn)實(shí)中經(jīng)常是 python 和java 兩中語言 相互調(diào)用 放案,之前一直使用 shell 去執(zhí)行 java jar 命令灰瞻,現(xiàn)在需要用到j(luò)ava 的 一些類,在嘗試使用py4j 抹剩,
簡單來說就是先裝上py4j的包蓖康,然后在Python環(huán)境中去執(zhí)行官網(wǎng)py4j的demo程序,但是遇到了一些問題黎烈。
py4j.protocol.Py4JNetworkError: An error occurred while trying to connect to the Java server (127.0.0.1:25333)
An error occurred while trying to connect to the Java server (127.0.0.1:25333)
后來找了stackoverflow上的一個(gè)答案py4j.protocol.Py4JNetworkError : An error occurred while trying to connect to the Java server知道了該怎么解決习柠,需要單獨(dú)開啟JavaGateway,這里運(yùn)用java的一個(gè)程序去開啟照棋。
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();
}
}
但是又遇到了一個(gè)問題资溃,
myTest.java:1: error: package py4j does not exist
是因?yàn)閜y4j的jar包沒有引入,于是在集群的目錄下找到了這個(gè)包必怜,不過某個(gè)博客說對(duì)于linux系統(tǒng)肉拓,作為系統(tǒng)級(jí)的庫,就會(huì)在/usr/share/py4j/py4j0.x.jar梳庆;而對(duì)于windows么就在C:\python27\share\py4j\py4j0.x.jar暖途,這個(gè)得看個(gè)人情況去找了。
于是我就將java程序與這個(gè)jar包放到一個(gè)目錄下執(zhí)行
javac -classpath ./py4j0.9.jar myTest.java
生成.class文件后
java -classpath .:./py4j0.9.jar myTest
便啟動(dòng)了JavaGateway
最后在Python的環(huán)境下執(zhí)行
>>> 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)