在java中調用python腳本有三種方式java
【方式一】:python
直接執行Python腳本代碼 引用 org.python包函數
1 PythonInterpreter interpreter = new PythonInterpreter(); 2 interpreter.exec("days=('mod','Tue','Wed','Thu','Fri','Sat','Sun'); "); ///執行python腳本
【方式二】:命令行
執行python .py文件日誌
1 PythonInterpreter interpreter = new PythonInterpreter(); 2 InputStream filepy = new FileInputStream("D:\\demo.py"); 3 interpreter.execfile(filepy); ///執行python py文件 4 filepy.close();
【方式三】:ip
對於前兩種方式可能存在如下問題:get
當python調用第三方函數庫的時候,不能調用。可是經過第三種方式能夠解決。it
直接上代碼:io
1.java代碼部分test
public static void Test1() throws Exception {
//TODO:執行python腳本
System.out.println("start python");
//需傳入的參數
String a = "aaa", b = "bbb", c = "ccc", d = "中國";
// System.out.println("start;;;" + a);
//設置命令行傳入參數
String[] argv = new String[] { "python", "data/pythonScrip/test1.py", a, b, c, d };
Process pr = Runtime.getRuntime().exec(argv);
System.err.println("pr:"+pr);
BufferedReader in = new BufferedReader(new InputStreamReader(pr.getInputStream(),"GBK"));
System.err.println("in:"+in);
String line;
// System.err.println(in.lines().count());
while ((line = in.readLine()) != null) {
System.out.println("line:"+line);
}
in.close();
pr.waitFor();
System.out.println("end");
}
2.python代碼部分(test1.py)
import sys
print("======")
print(sys.argv[0])
print(sys.argv[1])
print(sys.argv[2])
print(sys.argv[3])
print(sys.argv[4])
3.輸出結果
調用第三方函數庫案例
1.java代碼部分
public static void Test1() throws Exception {
//TODO:執行python腳本
System.out.println("start python");
//需傳入的參數
String a = "F:/6-日誌/20170822_主題相關進階/Demo/w2v_java_call/bd/w2v_bd.model", b = "一帶一路";
// System.out.println("start;;;" + a);
//設置命令行傳入參數
String[] argv = new String[] { "python", "data/pythonScrip/w2v_java.py", a, b};
Process pr = Runtime.getRuntime().exec(argv);
System.err.println("pr:"+pr);
BufferedReader in = new BufferedReader(new InputStreamReader(pr.getInputStream(),"GBK"));
System.err.println("in:"+in);
String line;
// System.err.println(in.lines().count());
while ((line = in.readLine()) != null) {
System.out.println("line:"+line);
}
in.close();
pr.waitFor();
System.out.println("end");
}
2.Python代碼部分
from gensim.models import word2vec #調用第三方函數庫
import sys
# def get_vector(word,model):
print (sys.argv[0]) #讀取動態參數,做爲python腳本的輸入
print (sys.argv[1])
print (sys.argv[2])
model = word2vec.Word2Vec.load(sys.argv[1])
vector=model[sys.argv[2]]
print(vector)
輸出結果