本文将主要介绍Java程序如何调用Python程序,并提供实现方式和步骤。
一、使用Runtime类执行Python脚本
Java提供了Runtime类来执行一些操作系统级别的操作,其中就包括启动外部进程执行Python脚本。我们可以通过调用Process类的方法来实现启动Python脚本的操作。
public class PythonExec{
public static void main(String[] args) {
String pythonPath = "python3";
String scriptPath = "/Users/abc/xxx.py";
try {
Process process = Runtime.getRuntime().exec(pythonPath+" "+scriptPath);
process.waitFor();
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = reader.readLine();
while (line != null) {
System.out.println(line);
line = reader.readLine();
}
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
}
上述代码中,我们使用了Runtime类来启动Python脚本,并通过BufferedReader来读取Python程序的标准输出。其中pythonPath指定了Python可执行文件的路径,scriptPath指定了要调用的Python脚本的路径。
二、使用ProcessBuilder类执行Python脚本
除了使用Runtime类外,我们也可以使用ProcessBuilder类来启动Python脚本。ProcessBuilder类提供了更加灵活的方法来启动外部进程。
public class PythonExec{
public static void main(String[] args) {
String pythonPath = "python3";
String scriptPath = "/Users/abc/xxx.py";
try {
ProcessBuilder processBuilder = new ProcessBuilder(pythonPath, scriptPath);
Process process = processBuilder.start();
process.waitFor();
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = reader.readLine();
while (line != null) {
System.out.println(line);
line = reader.readLine();
}
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
}
上述代码中,我们使用了ProcessBuilder类来启动Python脚本,并通过BufferedReader来读取Python程序的标准输出。同样地,pythonPath指定了Python可执行文件的路径,scriptPath指定了要调用的Python脚本的路径。
三、使用Jython库执行Python脚本
Jython是Java平台上的Python解释器,可以在Java代码中直接调用Python脚本。使用Jython可以使Python脚本与Java程序深度整合。
import org.python.util.PythonInterpreter;
import java.io.File;
public class PythonExec{
public static void main(String[] args) {
PythonInterpreter interpreter = new PythonInterpreter();
interpreter.exec("import sysnsys.path.append('/Users/abc')n"); //加入Python脚本所在路径
File file = new File("/Users/abc/xxx.py"); //Python脚本文件
interpreter.execfile(file.getAbsolutePath());
}
}
上述代码中,我们使用了Jython库的PythonInterpreter类来执行Python脚本。要使用PythonInterpreter类,需要先导入org.python.util.PythonInterpreter包。interpreter.exec()方法是在Python解释器中执行Python代码的方法,interpreter.execfile()方法可以执行一个Python脚本文件。
四、结论
本文介绍了Java程序调用Python程序的三种方式:使用Runtime类,使用ProcessBuilder类以及使用Jython库。通过本文的介绍,读者可以根据自己的需求选择合适的调用方式,并且掌握调用过程中的一些注意事项。