iis服务器助手广告广告
返回顶部
首页 > 资讯 > 后端开发 > Python >Java调用python代码的五种方式
  • 854
分享到

Java调用python代码的五种方式

javapythonJava调用python 2023-09-05 15:09:34 854人浏览 独家记忆

Python 官方文档:入门教程 => 点击学习

摘要

你还在纠结怎么样在Java中调用python吗?我们在实际工程项目问题中,经常会碰到不同语言代码之间互调的问题,比如此处的Java调用Python(常见Java调用python写的处理模型来完成数据处

你还在纠结怎么样在Java中调用python吗?我们在实际工程项目问题中,经常会碰到不同语言代码之间互调的问题,比如此处的Java调用Python(常见Java调用python写的处理模型来完成数据处理等)。

目录


让我们来看看具体怎么操作吧!

1. 无参数调用

说明: Java调用不带参数的python代码执行
样例代码如下:

try {String exe = "python解释器所处的绝对路径";String py = "python代码文件绝对地址";Process process = Runtime.getRuntime().exec(exe + " " + py);//获取结果的同时设置输入流编码格式"gb2312"InputStreamReader isr = new InputStreamReader(process.getInputStream(),"gb2312");LineNumberReader input = new LineNumberReader(isr);String result = "";result = input.readLine();System.out.println(result);input.close();isr.close();process.waitFor();} catch (InterruptedException | IOException e) {System.out.println("调用python脚本并读取结果时出错:" + e.getMessage());}

2. 带参数调用

带参调用可以将命令和参数写入String数组,然后作为执行参数执行。
基本语句如下:

String exe = "python解释器所处的绝对路径";String py = "python代码文件绝对地址";String pram = "单个传递参数,若参数为基本类型,转化为String;若为数组等类型,也是将其转换为String型";String [] args = new String[] {exe, py, pram...};Process process = Runtime.getRuntime().exec(args);

2.1. 单行返回值

说明: Java调用不带参数的python代码执行
样例代码如下:

try {String exe = "python解释器所处的绝对路径";String py = "python代码文件绝对地址";String pram = "单个传递参数,若参数为基本类型,转化为String;若为数组等类型,也是将其转换为String型";String [] args = new String[] {exe, py, pram...};Process process = Runtime.getRuntime().exec(args);//获取结果的同时设置输入流编码格式"gb2312"InputStreamReader isr = new InputStreamReader(process.getInputStream(),"gb2312");LineNumberReader input = new LineNumberReader(isr);String result = "";result = input.readLine();System.out.println(result);input.close();isr.close();process.waitFor();} catch (InterruptedException | IOException e) {System.out.println("调用python脚本并读取结果时出错:" + e.getMessage());}

2.2. 多行返回值

说明: Java调用不带参数的python代码执行
样例代码如下:

try {String exe = "python解释器所处的绝对路径";String py = "python代码文件绝对地址";String pram = "单个传递参数,若参数为基本类型,转化为String;若为数组等类型,也是将其转换为String型";String [] args = new String[] {exe, py, pram...};ProcessBuilder builder = new ProcessBuilder(args);    Process process = builder.start();    BufferedReader success = new BufferedReader(new InputStreamReader(process.getInputStream(), "GB2312"));//获取字符输入流对象    BufferedReader error = new BufferedReader(new InputStreamReader(process.getErrorStream(), "GB2312"));//获取错误信息的字符输入流对象    String line = null;    List<String> success_result = new ArrayList<>();    List<String> error_result = new ArrayList<>();    //记录输出结果    while ((line = success.readLine()) != null) {        success_result.add(line);    }    //记录错误信息    while ((line = error.readLine()) != null) {        error_result.add(line);    }    success.close();    error.close();    process.waitFor();    System.out.println(success_result);    System.out.println(error_result);} catch (InterruptedException | IOException e) {System.out.println("调用python脚本并读取结果时出错:" + e.getMessage());}

3. Java中直接执行python语句

注意: 此方法在使用之前需要导入依赖环境,如在Maven中导入如下依赖:

<dependency>    <groupId>org.pythongroupId>    <artifactId>jython-standaloneartifactId>        <version>3.7.0version>dependency>

调用语句如下:

import org.python.util.PythonInterpreterpublic class JavaRunPython {    public static void main(String[] args) {    //调用python的解释器        PythonInterpreter interpreter = new PythonInterpreter();        //执行Python语句        interpreter.exec("str = 'hello world!'; ");        interpreter.exec("print(str);");    }}

4. 通过PythonInterpreter直接调用python脚本

注意: 此方法也需要导入1.3中依赖
Java调用代码如下:

import org.python.util.PythonInterpreter;public class JavaPythonFile {    public static void main(String[] args) {        PythonInterpreter interpreter = new PythonInterpreter();        //我在这里使用相对路径,注意区分        interpreter.execfile("D:/code/test.py");    }}

test.py举例如下:

a = 1b = 2print(a +)

5. Java通过调用bat文件间接调用python

hello.bat测试代码如下:

echo hello world!D:cd D:\code\start python test.pypause

Java调用代码如下:

try {StringBuilder sb = new StringBuilder();String batPath = "D:/hello.bat";Process process = Runtime.getRuntime().exec(batPath);InputStream in = process.getInputStream();BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in));String line;while ((line = bufferedReader.readLine()) != null) {sb.append(line + "\n");}in.close();try {process.waitFor();} catch (InterruptedException e) {System.out.println(e);}} catch (IOException e) {System.out.println(e);}

如果大家有好的方法,欢迎交流评论!

来源地址:https://blog.csdn.net/qq_43522889/article/details/126776656

--结束END--

本文标题: Java调用python代码的五种方式

本文链接: https://www.lsjlt.com/news/395562.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作