使用Runtime.getRuntime()執行腳本文件,這種方式和.net下面調用cmd執行命令的方式類似。如果執行的python腳本有引用第三方包的,建議使用此種方式。
Process proc = Runtime.getRuntime().exec("python D:\\demo.py");
proc.waitFor();
Java調用代碼:
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Test5 {
public static void main(String[] args){
try{
System.out.println("start");
Process pr = Runtime.getRuntime().exec("d:\\python27\\python.exe test.py");
BufferedReader in = new BufferedReader(new
InputStreamReader(pr.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
in.close();
pr.waitFor();
System.out.println("end");
} catch (Exception e){
e.printStackTrace();
}
}
}
test.py的文件內容爲:
import sys
import urllib
print "hello"
print sys.path
java程序運行的結果爲:
start
hello
['D:\\eclipse_jee_workspace\\ZLabTest', 'C:\\Windows\\system32\\python27.zip', 'D:\\Python27\\DLLs', 'D:\\Python27\\lib', 'D:\\Python27\\lib\\plat-win', 'D:\\Python27\\lib\\lib-tk', 'D:\\Python27', 'D:\\Python27\\lib\\site-packages']
end