共計 1534 個字符,預計需要花費 4 分鐘才能閱讀完成。
在 Java 中調用 Python 腳本有多種方法,下面介紹兩種常用的方法:
- 使用
ProcessBuilder
類:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {public static void main(String[] args) throws IOException {ProcessBuilder pb = new ProcessBuilder("python", "path/to/your/python/script.py");
Process process = pb.start();
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {System.out.println(line);
}
int exitCode;
try {exitCode = process.waitFor();
} catch (InterruptedException e) {e.printStackTrace();
}
System.out.println("Python script exited with code: " + exitCode);
}
}
這種方法通過創建一個 ProcessBuilder
對象來執行 Python 腳本,并讀取 Python 腳本輸出的結果??梢允褂?ProcessBuilder
的start()
方法來啟動 Python 腳本,并使用 getInputStream()
方法獲取腳本輸出的結果。
- 使用
Runtime
類:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {public static void main(String[] args) throws IOException {String command = "python path/to/your/python/script.py";
Process process = Runtime.getRuntime().exec(command);
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {System.out.println(line);
}
int exitCode;
try {exitCode = process.waitFor();
} catch (InterruptedException e) {e.printStackTrace();
}
System.out.println("Python script exited with code: " + exitCode);
}
}
這種方法通過調用 Runtime
類的 exec()
方法來執行 Python 腳本,并讀取 Python 腳本輸出的結果。可以將要執行的 Python 命令傳遞給 exec()
方法,并使用 getInputStream()
方法獲取腳本輸出的結果。
無論使用哪種方法,都可以通過讀取 Python 腳本的輸出來獲取結果,并可以使用 waitFor()
方法等待腳本執行完畢,獲取腳本的退出碼。
丸趣 TV 網 – 提供最優質的資源集合!
正文完