Java执行Python代码的五种场景与示例方法

 更新时间:2025年07月29日 08:34:52   作者:yuanzhengme  
python可以搭建后端让Java调用接口,但某些时候我们用到的python代码可能并不多也许只有一个算法,此时就需要其他方法了,下面小编就来和大家详细介绍一下吧

1.为什么

python拥有的某些库要比Java强大,也拥有一些比Java更擅长的领域,python可以搭建后端让Java调用接口,但某些时候我们用到的python代码可能并不多也许只有一个算法,此时就需要以下方法了。

2.核心依赖

毫无疑问【自然是python的Java执行器了】

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

3.使用

3.1类型一【直接执行python代码】

public class ExecPythonCode {
    public static void main(String[] args) {
        PythonInterpreter interpreter = new PythonInterpreter();
        interpreter.exec("a=[5,2,3,9,4,0];");
        // 此处python语句是3.x版本的语法
        interpreter.exec("print(sorted(a));"); 
        // 此处是python语句是2.x版本的语法
        interpreter.exec("print sorted(a);"); 
        interpreter.close();
    }
}

3.2类型二【执行python文件后获取返回结果】

1.无参数的python文件执行

public class ExecPythonFile {
    public static void main(String[] args) {
        try {
            Process process = Runtime.getRuntime()
                    .exec("python D:\\PythonFile.py");
            BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line = null;
            while ((line = in.readLine()) != null) {
                System.out.println(line);
            }
            in.close();
            process.waitFor();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

2.带参数的python文件执行

public class ExecPythonFileWithArgs {
    public static void main(String[] args) {
        int a = 18, b = 19;
        args = new String[] { "python","D:\\PythonFileWithArgs.py",
        String.valueOf(a), String.valueOf(b) };
        try {
            Process process = Runtime.getRuntime().exec(args);
            BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line = null;
            while ((line = in.readLine()) != null) {
                System.out.println(line);
            }
            in.close();
            process.waitFor();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

3.【Windows环境】使用bat脚本执行python文件【我猜想也是有Linux环境的执行方法的】

public class ExecPythonBat {
    public static void main(String[] args) {
        try {
            Process process = Runtime.getRuntime().exec("cmd /c D:\\RunPythonFile.bat");
            BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line = null;
            while ((line = in.readLine()) != null) {
                System.out.println(line);
            }
            in.close();
            process.waitFor();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

3.3类型三【读取python文件内的函数进行执行】

public class ExecPythonFileCode {
    public static void main(String[] args) {
        PythonInterpreter interpreter = new PythonInterpreter();
        interpreter.execfile("D:\\PythonFile.py");
        PyFunction function = interpreter.get("add", PyFunction.class);
        int a = 3, b = 12;
        PyObject pyObject = function.__call__(new PyInteger(a), new PyInteger(b));
        System.out.println("The result is : " + pyObject);
        interpreter.close();
    }
}

4.python文件和执行脚本

文件一:PythonFile.py

import numpy as np
a = np.arange(12).reshape(3,4)
print(a)
def add(a,b):
    return a+b;

文件二:PythonFileWithArgs.py

import sys
 
def func(a,b):
    return (a+b)
 
if __name__ == '__main__':
    a = []
    for i in range(1, len(sys.argv)):
        a.append((int(sys.argv[i])))
    print(func(a[0],a[1]))

文件三:RunPythonFile.bat

@echo off
cmd /k python E:\Anaconda3_Python\PythonFile.py

到此这篇关于Java执行Python代码的五种场景与示例方法的文章就介绍到这了,更多相关Java执行Python代码内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

相关文章

  • Spring boot实现数据库读写分离的方法

    Spring boot实现数据库读写分离的方法

    本篇文章主要介绍了Spring boot实现数据库读写分离的方法,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-01-01
  • 详解Spring中bean生命周期回调方法

    详解Spring中bean生命周期回调方法

    本篇文章主要介绍了详解Spring中bean生命周期回调方法,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2017-07-07
  • 浅谈MyBatis所有的jdbcType类型

    浅谈MyBatis所有的jdbcType类型

    在Mybatis中JdbcType类型是一个枚举类型,它包含了所有的JDBC数据类型,如VARCHAR、INTEGER、DATE等,本文主要介绍了浅谈MyBatis所有的jdbcType类型,具有一定的参考价值,感兴趣的可以了解一下
    2023-06-06
  • SpringBoot实现使用反射模拟IOC和getBean

    SpringBoot实现使用反射模拟IOC和getBean

    这篇文章主要介绍了SpringBoot实现使用反射模拟IOC和getBean,IOC就是spring的核心思想之一——控制反转。这里不再赘述,看此文章即可了解
    2023-04-04
  • Java堆外内存及调优方式

    Java堆外内存及调优方式

    直接内存并不是Java虚拟机规范中定义的内存区域,但使用广泛,它能显著提高IO性能,避免内存复制,然而,它也需要小心管理,以避免内存泄漏和溢出,通过设置参数和使用NMT特性,可以更好地管理和诊断直接内存
    2026-04-04
  • java导出pdf文件的详细实现方法

    java导出pdf文件的详细实现方法

    这篇文章主要介绍了java导出pdf文件的详细实现方法,包括制作模板、获取中文字体文件、实现后端服务以及前端发起请求并生成下载链接,需要的朋友可以参考下
    2025-03-03
  • SpringBoot利用Validation包实现高效参数校验

    SpringBoot利用Validation包实现高效参数校验

    如果不进行校验就直接使用这些数据,可能会导致各种问题,那么SpringBoot如何利用Validation包实现高效参数校验呢,下面让我们一起来探讨这个重要的话题吧
    2025-04-04
  • 手把手带你了解Java-Stream流方法学习及总结

    手把手带你了解Java-Stream流方法学习及总结

    这篇文章主要介绍了通过实例了解JavaStream流的方法学习和总结,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2021-08-08
  • springboot基于docsify 实现随身文档

    springboot基于docsify 实现随身文档

    这篇文章主要介绍了springboot基于docsify实现随身文档的相关资料,需要的朋友可以参考下
    2022-09-09
  • springcloud之Feign、ribbon如何设置超时时间和重试机制

    springcloud之Feign、ribbon如何设置超时时间和重试机制

    这篇文章主要介绍了springcloud之Feign、ribbon如何设置超时时间和重试机制,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-08-08

最新评论