Spring boot 集成python引擎快速入门demo

一、Python 介绍

Python 是一个高层次的结合了解释性、编译性、互动性和面向对象的脚本语言。 Python 的设计具有很强的可读性,相比其他语言经常使用英文关键字,其他语言的一些标点符号,它具有比其他语言更有特色语法结构。

  • Python 是一种解释型语言: 这意味着开发过程中没有了编译这个环节。类似于PHP和Perl语言。
  • Python 是交互式语言: 这意味着,您可以在一个 Python 提示符 >>> 后直接执行代码。
  • Python 是面向对象语言: 这意味着Python支持面向对象的风格或代码封装在对象的编程技术。
  • **Python 是初学者的语言:**Python 对初级程序员而言,是一种伟大的语言,它支持广泛的应用程序开发,从简单的文字处理到 WWW 浏览器再到游戏。

二、代码工程

pom.xml

xml 复制代码
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>springboot-demo</artifactId>
        <groupId>com.et</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>python</artifactId>

    <properties>
        <maven.compiler.source>8</maven.compiler.source>
        <maven.compiler.target>8</maven.compiler.target>
    </properties>
    <dependencies>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-autoconfigure</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!--Maven依赖,jar包自行前往仓库下载-->
        <dependency>
            <groupId>org.python</groupId>
            <artifactId>jython-standalone</artifactId>
            <version>2.7.0</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
    </dependencies>
</project>

application.yaml

yaml 复制代码
server:
  port: 8088

DemoApplication.java

typescript 复制代码
package com.et.python;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoApplication {

   public static void main(String[] args) {
      SpringApplication.run(DemoApplication.class, args);
   }
}

代码仓库

三、测试

1.在java类中直接执行python语句

java 复制代码
package com.et.python.util;

import org.python.util.PythonInterpreter;

public class JavaRunPython {
    
    public static void main(String[] args) {
        PythonInterpreter interpreter = new PythonInterpreter();
        interpreter.exec("a='hello world'; ");
        interpreter.exec("print a;");
    }

}

执行结果

复制代码
hello world

2.在java中直接调用python脚本

在resource/py文件夹下创建一个python脚本,文件名字为test.py,文件内容如下:

css 复制代码
a = 1
b = 2
print (a + b)

创建JavaPythonFile.java类,内容如下:

swift 复制代码
package com.et.python.util;

import org.python.util.PythonInterpreter;

public class JavaPythonFile {

    public static void main(String[] args) {
        PythonInterpreter interpreter = new PythonInterpreter();
        interpreter.execfile("D:\\IdeaProjects\\ETFramework\\python\\src\\main\\resources\\py\\test.py");
    }
}

执行结果

复制代码
3

3.使用Runtime.getRuntime()执行python脚本文件,推荐使用

在resource/py文件夹下创建一个python脚本,文件名字为runtime.py,文件内容如下:

bash 复制代码
print('RuntimeDemo')

java调用代码如下

java 复制代码
package com.et.python.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

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

执行结果

复制代码
RuntimeDemo

4.调用python脚本中的函数

在resource/py文件夹下创建一个python脚本,文件名字为add.py,文件内容如下:

python 复制代码
def add(a,b):
    return a + b

创建Function.java类,内容如下:

java 复制代码
package com.et.python.util;

import org.python.core.PyFunction;
import org.python.core.PyInteger;
import org.python.core.PyObject;
import org.python.util.PythonInterpreter;

public class Function {
    
    public static void main(String[] args) {
        PythonInterpreter interpreter = new PythonInterpreter();
        interpreter.execfile("D:\\IdeaProjects\\ETFramework\\python\\src\\main\\resources\\py\\add.py");
                
        // 第一个参数为期望获得的函数(变量)的名字,第二个参数为期望返回的对象类型
        PyFunction pyFunction = interpreter.get("add", PyFunction.class);
        int a = 5, b = 10;
        //调用函数,如果函数需要参数,在Java中必须先将参数转化为对应的"Python类型"
        PyObject pyobj = pyFunction.__call__(new PyInteger(a), new PyInteger(b)); 
        System.out.println("the anwser is: " + pyobj);
    }

}

执行结果

csharp 复制代码
the anwser is: 15

四、引用

相关推荐
abcy07121314 分钟前
python flask app.py里的接口放在别的目录下图文教程
python
弹简特20 分钟前
【零基础学Python】08-Python面向对象之封装、多态和函数进阶
开发语言·python
人道领域23 分钟前
一篇文章解决Codex的安装,实操一遍过
java·开发语言·codex
专注VB编程开发20年34 分钟前
工控上位机开发为什么固死.net 4.5.2sdk?适配win7
python·信息可视化·c#
郑州光合科技余经理36 分钟前
海外版外卖系统:如何快速搭建国际化外卖平台
java·开发语言·前端·人工智能·小程序·系统架构·php
CC数学建模38 分钟前
2026第八届中青杯全国大学生数学建模竞赛C题:情绪维度耦合约束的脑电信号情绪识别 (1)完整思路、代码、模型、文章,全网首发高质量分享!
python·算法·数学建模
Kobebryant-Manba41 分钟前
安装cuda
pytorch·python·深度学习·conda·numpy
Yvonne爱编码41 分钟前
JAVA EE初阶---DAY 1 计算机是如何工作的
java·java-ee
小何code41 分钟前
【Python零基础入门】第10篇:Python列表方法与应用实例
数据库·人工智能·python
CC数学建模41 分钟前
2026第八届中青杯全国大学生数学建模竞赛B题:AI生成内容的质量评估与参数优化完整思路、代码、模型、文章,全网首发高质量分享!
python·算法·数学建模