Python在Java中的調(diào)用并不是直接運(yùn)行Python代碼,而是通過Java程序調(diào)用Python解釋器來執(zhí)行Python腳本。以下是一些在Java中調(diào)用Python的技巧:
try {
ProcessBuilder pb = new ProcessBuilder("python", "myscript.py");
Process process = pb.start();
// 可以使用process.getInputStream()、process.getOutputStream()和process.getErrorStream()來讀取和寫入進(jìn)程的輸入/輸出/錯(cuò)誤流
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();
}