Java調用Python腳本有多種方式這裡隻利用其中一種常用的
public static void main(String[] args) {
String[] arguments = new String[] { "python", "pythonScript/OptiAllcation.py"};//{"指定Python調用",Python腳本絕對路徑}
try {
Process process = Runtime.getRuntime().exec(arguments);
BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = null;
while ((line = in.readLine()) != null) {
System.out.println(line);//腳本傳回值
}
in.close();
int re = process.waitFor();// re = 0 表示調用成功; re= 1 表示調用失敗
System.out.println(re);
} catch (Exception e) {
e.printStackTrace();
}
}
這種方式相當于利用隐形cmd視窗調用 ,即類似于直接在cmd視窗中寫指令: Python 腳本路徑;
//注意請先確定腳本能正确運作,再考慮Java的調用