java 执行Python程序的三种实现方式
off999 2024-10-11 14:04 54 浏览 0 评论
在 Java 中执行 Python 程序有多种实现方式,以下是几种常见的方法:
1. 使用 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 class 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
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 class 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 依赖到你的项目中(如果你使用的是 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 class 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 程序,并根据需要处理输出和错误信息。
未完待续,喜欢的点个关注 谢谢。
相关推荐
- Python Flask 容器化应用链路可观测
-
简介Flask是一个基于Python的轻量级Web应用框架,因其简洁灵活而被称为“微框架”。它提供了Web开发所需的核心功能,如请求处理、路由管理等,但不会强制开发者使用特定的工具或库。...
- Python GUI应用开发快速入门(python开发软件教程)
-
一、GUI开发基础1.主流GUI框架对比表1PythonGUI框架比较框架特点适用场景学习曲线Tkinter内置库,简单小型应用,快速原型平缓PyQt功能强大,商用许可专业级桌面应用陡峭PySi...
- 实战揭秘:Python Toga 打造跨平台 GUI 应用的神奇之旅
-
在Python的世界里,GUI(图形用户界面)开发工具众多,但要找到一款真正跨平台、易于使用且功能强大的工具并不容易。今天,我们就来深入探讨一下Toga——一款Python原生、操作系统原...
- python应用目录规划(python的目录)
-
Python大型应用目录结构规划(企业级最佳实践)核心原则模块化:按业务功能拆分,高内聚低耦合可扩展性:支持插件机制和动态加载环境隔离:清晰区分开发/测试/生产环境自动化:内置标准化的构建测试部署流...
- Python图形化应用开发框架:PyQt开发简介
-
PyQt概述定义:PyQt是Python绑定Qt框架的工具集,用于开发跨平台GUI应用程序原理:通过Qt的C++库提供底层功能,PyQt使用SIP工具生成Python绑定特点:支持Windows/ma...
- [python] 基于PyOD库实现数据异常检测
-
PyOD是一个全面且易于使用的Python库,专门用于检测多变量数据中的异常点或离群点。异常点是指那些与大多数数据点显著不同的数据,它们可能表示错误、噪声或潜在的有趣现象。无论是处理小规模项目还是大型...
- Python、Selenium 和 Allure 进行 UI 自动化测试的简单示例脚本
-
环境准备确保你已经安装了以下库:SeleniumAllurepytest你可以使用以下命令安装所需库:pipinstallseleniumallure-pytestpytest示例代码下面的代...
- LabVIEW 与 Python 融合:打造强大测试系统的利器
-
在现代测试系统开发领域,LabVIEW和Python各自凭借独特优势占据重要地位。LabVIEW以图形化编程、仪器控制和实时系统开发能力见长;Python则凭借丰富的库资源、简洁语法和强大数...
- 软件测试进阶之自动化测试——python+appium实例
-
扼要:1、了解python+appium进行APP的自动化测试实例;2、能根据实例进行实训操作;本课程主要讲述用python+appium对APP进行UI自动化测试的例子。appium支持Androi...
- Python openpyxl:读写样式Excel一条龙,测试报表必备!
-
无论你是测试工程师、数据分析师,还是想批量导出Excel的自动化工作者,只需一个库openpyxl,即可高效搞定Excel的各种需求!为什么选择openpyxl?支持.xlsx格式...
- Python + Pytest 测试框架——数据驱动
-
引言前面已经和大家介绍过Unittest测试框架的数据驱动框架DDT,以及其实现原理。今天和大家分享的是Pytest测试框架的数据驱动,Pytest测试框架的数据驱动是由pytest自...
- 这款开源测试神器,圆了我玩游戏不用动手的梦想
-
作者:HelloGitHub-Anthony一天我在公司用手机看游戏直播,同事问我在玩什么游戏?我和他说在看直播,他恍然大悟:原来如此,我还纳闷你玩游戏,咋不用动手呢。。。。一语惊醒梦中人:玩游戏不用...
- Python单元测试框架对比(pycharm 单元测试)
-
一、核心框架对比特性unittest(标准库)pytest(主流第三方)nose2(unittest扩展)doctest(文档测试)安装Python标准库pipinstallpytestp...
- 利用机器学习,进行人体33个2D姿态检测与评估
-
前几期的文章,我们分享了人脸468点检测与人手28点检测的代码实现过程,本期我们进行人体姿态的检测与评估通过视频进行人体姿势估计在各种应用中起着至关重要的作用,例如量化体育锻炼,手语识别和全身手势控制...
你 发表评论:
欢迎- 一周热门
- 最近发表
-
- Python Flask 容器化应用链路可观测
- Python GUI应用开发快速入门(python开发软件教程)
- 【MCP实战】Python构建MCP应用全攻略:从入门到实战!
- 实战揭秘:Python Toga 打造跨平台 GUI 应用的神奇之旅
- python应用目录规划(python的目录)
- Python图形化应用开发框架:PyQt开发简介
- [python] 基于PyOD库实现数据异常检测
- Python、Selenium 和 Allure 进行 UI 自动化测试的简单示例脚本
- LabVIEW 与 Python 融合:打造强大测试系统的利器
- 软件测试进阶之自动化测试——python+appium实例
- 标签列表
-
- python计时 (73)
- python安装路径 (56)
- python类型转换 (93)
- python进度条 (67)
- python吧 (67)
- python字典遍历 (54)
- python的for循环 (65)
- python格式化字符串 (61)
- python静态方法 (57)
- python列表切片 (59)
- python面向对象编程 (60)
- python 代码加密 (65)
- python串口编程 (77)
- python读取文件夹下所有文件 (59)
- java调用python脚本 (56)
- python操作mysql数据库 (66)
- python获取列表的长度 (64)
- python接口 (63)
- python调用函数 (57)
- python多态 (60)
- python匿名函数 (59)
- python打印九九乘法表 (65)
- python赋值 (62)
- python异常 (69)
- python元祖 (57)