JAVA調python指令碼
來源:互聯網
上載者:User
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) {
try {
System.out.println("start");
Process pr = Runtime.getRuntime().exec("python 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();
}
}
}
如果在eclipse中直接運行報如下錯誤:
java.io.IOException: Cannot run program "python": CreateProcess error=2
則配置Run Configuration中的Enviroment,增加PATH變數,見附件:
在java application中調用Process proc = Runtime.getRuntime().exec("python xx.py");是可以的【xx.py直接位於工程目錄下面】
在tomcat中的servlet中使用Process proc = Runtime.getRuntime().exec("python xx.py");時,開始是沒反應。 排查結果應該是pyhon命令可以找到(或者直接輸入e:\\Python\\python.exe絕對路徑) x.x.py 檔案我是放在根目錄下,故意把名字寫錯成xy.py.,結果都是沒反應【彷彿這條語句沒有執行】
=》應該是py檔案找不到。我用了絕對路徑搜尋py檔案。Process proc = Runtime.getRuntime().exec("python d:\\xx.py");這個倒是可以。
【目前總結 就是py檔案的路徑問題】