Python在Java中的調用并不是直接運行Python代碼,而是通過Java程序調用Python解釋器來執行Python腳本。以下是一些在Java中調用Python的技巧:
try {
ProcessBuilder pb = new ProcessBuilder("python", "myscript.py");
Process process = pb.start();
// 可以使用process.getInputStream()、process.getOutputStream()和process.getErrorStream()來讀取和寫入進程的輸入/輸出/錯誤流
int exitCode = process.waitFor();
System.out.println("Exit code: " + exitCode);
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
ProcessBuilder pb = new ProcessBuilder("python", "myscript.py", "arg1", "arg2");
try {
ProcessBuilder pb = new ProcessBuilder("python", "myscript.py");
Process process = pb.start();
Thread outputThread = new Thread(() -> {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
});
outputThread.start();
int exitCode = process.waitFor();
outputThread.join();
System.out.println("Exit code: " + exitCode);
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
try {
ProcessBuilder pb = new ProcessBuilder("python", "myscript.py");
Process process = pb.start();
Thread errorThread = new Thread(() -> {
try (BufferedReader reader = new BufferedReader(new InputStreamReader(process.getErrorStream()))) {
String line;
while ((line = reader.readLine()) != null) {
System.err.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
});
errorThread.start();
int exitCode = process.waitFor();
errorThread.join();
System.out.println("Exit code: " + exitCode);
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}