百度360必应搜狗淘宝本站头条
当前位置:网站首页 > 技术资源 > 正文

Spring boot 调用python,怎么办?

off999 2024-10-11 14:03 39 浏览 0 评论

一、Python 介绍

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

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


二、代码工程


pom.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

server:

  port: 8088


DemoApplication.java

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);

   }

}


代码仓库

  • https://github.com/Harries/springboot-demo


三、测试


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

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,文件内容如下:

a = 1
b = 2
print (a + b)

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

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,文件内容如下:

print('RuntimeDemo')

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,文件内容如下:

def add(a,b):

    return a + b

创建Function.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);

    }
}

执行结果

the anwser is: 15

相关推荐

面试官:来,讲一下枚举类型在开发时中实际应用场景!

一.基本介绍枚举是JDK1.5新增的数据类型,使用枚举我们可以很好的描述一些特定的业务场景,比如一年中的春、夏、秋、冬,还有每周的周一到周天,还有各种颜色,以及可以用它来描述一些状态信息,比如错...

一日一技:11个基本Python技巧和窍门

1.两个数字的交换.x,y=10,20print(x,y)x,y=y,xprint(x,y)输出:102020102.Python字符串取反a="Ge...

Python Enum 技巧,让代码更简洁、更安全、更易维护

如果你是一名Python开发人员,你很可能使用过enum.Enum来创建可读性和可维护性代码。今天发现一个强大的技巧,可以让Enum的境界更进一层,这个技巧不仅能提高可读性,还能以最小的代价增...

Python元组编程指导教程(python元组的概念)

1.元组基础概念1.1什么是元组元组(Tuple)是Python中一种不可变的序列类型,用于存储多个有序的元素。元组与列表(list)类似,但元组一旦创建就不能修改(不可变),这使得元组在某些场景...

你可能不知道的实用 Python 功能(python有哪些用)

1.超越文件处理的内容管理器大多数开发人员都熟悉使用with语句进行文件操作:withopen('file.txt','r')asfile:co...

Python 2至3.13新特性总结(python 3.10新特性)

以下是Python2到Python3.13的主要新特性总结,按版本分类整理:Python2到Python3的重大变化Python3是一个不向后兼容的版本,主要改进包括:pri...

Python中for循环访问索引值的方法

技术背景在Python编程中,我们经常需要在循环中访问元素的索引值。例如,在处理列表、元组等可迭代对象时,除了要获取元素本身,还需要知道元素的位置。Python提供了多种方式来实现这一需求,下面将详细...

Python enumerate核心应用解析:索引遍历的高效实践方案

喜欢的条友记得关注、点赞、转发、收藏,你们的支持就是我最大的动力源泉。根据GitHub代码分析统计,使用enumerate替代range(len())写法可减少38%的索引错误概率。本文通过12个生产...

Python入门到脱坑经典案例—列表去重

列表去重是Python编程中常见的操作,下面我将介绍多种实现列表去重的方法,从基础到进阶,帮助初学者全面掌握这一技能。方法一:使用集合(set)去重(最简单)pythondefremove_dupl...

Python枚举类工程实践:常量管理的标准化解决方案

本文通过7个生产案例,系统解析枚举类在工程实践中的应用,覆盖状态管理、配置选项、错误代码等场景,适用于Web服务开发、自动化测试及系统集成领域。一、基础概念与语法演进1.1传统常量与枚举类对比#传...

让Python枚举更强大!教你玩转Enum扩展

为什么你需要关注Enum?在日常开发中,你是否经常遇到这样的代码?ifstatus==1:print("开始处理")elifstatus==2:pri...

Python枚举(Enum)技巧,你值得了解

枚举(Enum)提供了更清晰、结构化的方式来定义常量。通过为枚举添加行为、自动分配值和存储额外数据,可以提升代码的可读性、可维护性,并与数据库结合使用时,使用字符串代替数字能简化调试和查询。Pytho...

78行Python代码帮你复现微信撤回消息!

来源:悟空智能科技本文约700字,建议阅读5分钟。本文基于python的微信开源库itchat,教你如何收集私聊撤回的信息。[导读]Python曾经对我说:"时日不多,赶紧用Python"。于是看...

登录人人都是产品经理即可获得以下权益

文章介绍如何利用Cursor自动开发Playwright网页自动化脚本,实现从选题、写文、生图的全流程自动化,并将其打包成API供工作流调用,提高工作效率。虽然我前面文章介绍了很多AI工作流,但它们...

Python常用小知识-第二弹(python常用方法总结)

一、Python中使用JsonPath提取字典中的值JsonPath是解析Json字符串用的,如果有一个多层嵌套的复杂字典,想要根据key和下标来批量提取value,这是比较困难的,使用jsonpat...

取消回复欢迎 发表评论: