java执行Python程序的三种实现方式

编程探索课程 2024-07-23 16:52:35

在 Java 中执行 Python 程序有多种实现方式,以下是几种常见的方法:

1. 使用 ProcessBuilder

ProcessBuilder 执行外部进程

ProcessBuilder 是 Java 提供的一个类,可以用来启动和控制外部进程。以下是一个示例代码,展示了如何使用 ProcessBuilder 执行 Python 脚本:

import java.io.BufferedReader;import java.io.IOException;import java.io.InputStream;import java.io.InputStreamReader;import java.util.ArrayList;import java.util.List;public ExecutePythonScript { public static void main(String[] args) { // 创建命令列表 List<String> command = new ArrayList<>(); command.add("python"); command.add("path/to/your/script.py"); command.add("arg1"); // 可选:传递给 Python 脚本的参数 // 创建 ProcessBuilder 实例 ProcessBuilder processBuilder = new ProcessBuilder(command); try { // 启动进程 Process process = processBuilder.start(); // 获取标准输出流 InputStream inputStream = process.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); String line; System.out.println("Standard Output:"); while ((line = reader.readLine()) != null) { System.out.println(line); } // 获取标准错误流 InputStream errorStream = process.getErrorStream(); BufferedReader errorReader = new BufferedReader(new InputStreamReader(errorStream)); System.out.println("Error Output:"); while ((line = errorReader.readLine()) != null) { System.out.println(line); } // 等待进程结束并获取退出值 int exitCode = process.waitFor(); System.out.println("Process exit code: " + exitCode); } catch (IOException | InterruptedException e) { e.printStackTrace(); } }}

在这个示例中:

- command 列表包含了要执行的命令和参数。

- processBuilder.start() 启动进程。

- 通过 process.getInputStream() 和 process.getErrorStream() 获取标准输出和标准错误流。

- process.waitFor() 等待进程结束并获取退出值。

2. 使用 Jython

Jpython

Jython 是一个在 Java 平台上实现的 Python 解释器,它允许你在 Java 代码中直接执行 Python 代码。以下是一个简单的示例:

首先,添加 Jython 依赖到你的项目中(如果你使用的是 Maven,可以在 `pom.xml` 中添加以下依赖):

<dependency> <groupId>org.python</groupId> <artifactId>jython-standalone</artifactId> <version>2.7.2</version></dependency>

然后,使用 Jython 执行 Python 代码:

import org.python.util.PythonInterpreter;public ExecutePythonWithJython { public static void main(String[] args) { try (PythonInterpreter pyInterp = new PythonInterpreter()) { pyInterp.exec("print('Hello from Python!')"); } }}

在这个示例中:

- PythonInterpreter 是 Jython 提供的一个类,用于执行 Python 代码。

- pyInterp.exec("print('Hello from Python!')") 执行 Python 代码。

3. 使用 Apache Commons Exec

Apache Commons Exec 是一个用于执行外部进程的库,它提供了比 ProcessBuilder 更高级的功能。以下是一个示例:

Apache Commons Exec 实现原理

首先,添加 Apache Commons Exec 依赖到你的项目中(如果你使用的是 Maven,可以在 `pom.xml` 中添加以下依赖):

<dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-exec</artifactId> <version>1.3</version></dependency>

然后,使用 Apache Commons Exec 执行 Python 脚本:

import org.apache.commons.exec.CommandLine;import org.apache.commons.exec.DefaultExecutor;import org.apache.commons.exec.ExecuteWatchdog;import org.apache.commons.exec.PumpStreamHandler;import java.io.ByteArrayOutputStream;import java.io.IOException;public ExecutePythonWithCommonsExec { public static void main(String[] args) { CommandLine cmdLine = new CommandLine("python"); cmdLine.addArgument("path/to/your/script.py"); cmdLine.addArgument("arg1"); // 可选:传递给 Python 脚本的参数 ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); PumpStreamHandler streamHandler = new PumpStreamHandler(outputStream); DefaultExecutor executor = new DefaultExecutor(); executor.setStreamHandler(streamHandler); ExecuteWatchdog watchdog = new ExecuteWatchdog(60000); // 设置超时时间 executor.setWatchdog(watchdog); try { int exitCode = executor.execute(cmdLine); System.out.println("Process exit code: " + exitCode); System.out.println("Output: " + outputStream.toString()); } catch (IOException e) { e.printStackTrace(); } }}

在这个示例中:

- CommandLine 用于构建要执行的命令。

- DefaultExecutor 用于执行命令。

- PumpStreamHandler 用于处理标准输出和标准错误流。

- ExecuteWatchdog 用于设置超时时间。

通过这些方法,你可以在 Java 中执行 Python 程序,并根据需要处理输出和错误信息。

未完待续,喜欢的点个关注 谢谢。

创作不易 点个关注 谢谢

0 阅读:22

编程探索课程

简介:感谢大家的关注