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

四、引用

相关推荐
cpolar技术支持3 分钟前
中文文件名排序跟拼音对不上:os.listdir 返回的是文件系统顺序,三个中文名按字节排结果正好相反
python·文件系统·cpolar·编码·排序
Thanks_ks7 分钟前
【第 008 讲】在终端中运行 Python 程序:交互模式与脚本模式 | 绝对路径与相对路径 | 以模块方式运行 | 常见报错的识别与排查
python·异常处理·终端·脚本·命令行·cmd·python 解释器
威哥爱编程16 分钟前
模拟面试智能体开发实战 08:总评报告先过三道闸,防泄题防夸大防错建议,才敢发到候选人手上
python·agent·harmonyos
文丑颜不良啊16 分钟前
LeetCode2741~2760题目解析
java·leetcode
郝学胜-神的一滴21 分钟前
LangChain Skill 实现(渐进披露 On-Demand Skill,LangChain 官方 Deep Agent Skill 模式)
开发语言·python·langchain·numpy
金銀銅鐵10 小时前
带您看懂字节码指令(二):空循环里有什么
java·后端·ai编程
投图匠11 小时前
十种不同风格的 CTP接口 框架
开发语言·python
吴名氏.11 小时前
Java转AI Agent教程(第十三周)混合检索与重排
java·数据库·人工智能·ai·ai agent
.痞老板.12 小时前
java ee--多线程(进阶)
java·java-ee
2601_9679801112 小时前
深入理解词向量算法及其在Python中的实践
python·word2vec·glove·fasttext·词向量