1背景
java雖然很強大,但是在處理一些特定的工作的時候,一些腳本語言還有有著得天獨厚的優勢,例如在linux服務器上進行一些列的部署操作,就需要調用shell腳本,亦或者我們需要進行一些科學計算,多方研究表明python有相應的第三方庫可以完成需求,并且性能不差,此時我們便有必要調用python腳本。
2舉例
我們可以使用java自帶的Runtime.getRuntime().exec()
方法進行調用,先來看一個調用python腳本的例子吧。
public class InvokePyDemo {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("please input a number: ");
String num = scanner.next();
Process process = null;
/**
* @參數1:“python”是要調用的腳本類型
* @參數2: “<dir>/<name>.py”是腳本具體的路徑,根據需要使用相對路徑或絕對路徑
* @參數3:這是給腳本傳遞的第一個參數,參數數量不限
* python可使用sys.argv[1]接受傳入的第一個參數。以此類推
*/
String[] args1 = new String[]{"python", "<dir>/<name>.py", num};
try {
process = Runtime.getRuntime().exec(args1);
BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
in.close();
process.waitFor();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}