```markdown
在现代软件开发中,经常需要将不同语言编写的程序进行互操作。Java 和 Python 是最常用的两种编程语言之一。本文将介绍如何在 Java 程序中调用 Python 脚本并获取执行结果。
ProcessBuilder
调用 Python 脚本Java 可以通过 ProcessBuilder
类来启动外部程序并获取其输出。我们可以利用这个机制,调用 Python 脚本并获取其结果。
```java import java.io.BufferedReader; import java.io.InputStreamReader;
public class JavaPythonExample { public static void main(String[] args) { try { // 创建 ProcessBuilder,指定 Python 和脚本路径 ProcessBuilder processBuilder = new ProcessBuilder("python", "script.py");
// 启动进程并获取执行结果
Process process = processBuilder.start();
// 获取 Python 脚本的输出
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line); // 打印 Python 脚本的输出
}
// 等待 Python 脚本执行完毕
int exitCode = process.waitFor();
System.out.println("Python 脚本执行完毕,退出码:" + exitCode);
} catch (Exception e) {
e.printStackTrace();
}
}
} ```
ProcessBuilder
用于启动外部进程,这里我们指定了调用 python
和脚本 script.py
。BufferedReader
来读取 Python 脚本的标准输出流。process.waitFor()
等待 Python 脚本执行完毕并获取退出码。在运行 Java 代码之前,确保你已经安装了 Python,并且脚本 script.py
在指定路径下。例如,script.py
的内容如下:
```python
print("Hello from Python!") ```
如果需要向 Python 脚本传递参数,可以通过 ProcessBuilder
的命令行参数进行传递。
```java import java.io.BufferedReader; import java.io.InputStreamReader;
public class JavaPythonExampleWithArgs { public static void main(String[] args) { try { // 创建 ProcessBuilder,传递参数给 Python 脚本 ProcessBuilder processBuilder = new ProcessBuilder("python", "script.py", "arg1", "arg2");
// 启动进程并获取执行结果
Process process = processBuilder.start();
// 获取 Python 脚本的输出
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line); // 打印 Python 脚本的输出
}
// 等待 Python 脚本执行完毕
int exitCode = process.waitFor();
System.out.println("Python 脚本执行完毕,退出码:" + exitCode);
} catch (Exception e) {
e.printStackTrace();
}
}
} ```
```python
import sys print("Received arguments:", sys.argv) ```
Received arguments: ['script.py', 'arg1', 'arg2']
除了通过外部进程调用 Python 脚本,另一种方法是使用 Jython,它是一个可以运行 Python 代码的 Java 平台实现。通过 Jython,你可以直接在 Java 中执行 Python 代码。
```java import org.python.util.PythonInterpreter;
public class JavaPythonJythonExample { public static void main(String[] args) { try { // 创建 Python 解释器实例 PythonInterpreter interpreter = new PythonInterpreter();
// 执行 Python 代码
interpreter.exec("print('Hello from Jython!')");
} catch (Exception e) {
e.printStackTrace();
}
}
} ```
要使用 Jython,首先需要在 Java 项目中引入 Jython 库。可以通过 Maven 来引入 Jython 依赖:
xml
<dependency>
<groupId>org.python</groupId>
<artifactId>jython-standalone</artifactId>
<version>2.7.2</version>
</dependency>
Hello from Jython!
在选择方法时,需要根据项目的需求来决定,ProcessBuilder
适合与 Python 代码的隔离,而 Jython 更适合紧密集成的场景。
```