在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()
方法等待脚本执行完毕,获取脚本的退出码。