You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot集成Azure DevOps中Python制品的调用方法问询

解决Python制品在Spring Boot项目中的调用问题

首先明确核心事实:Maven仅负责将Python制品下载到本地仓库,但Java无法直接导入并调用Python方法——两者属于不同运行时环境,必须通过跨语言交互方案实现。以下是几种可行的落地方式:

方案1:封装为HTTP服务(最通用低耦合)

把Python制品的功能包装成REST接口,通过HTTP请求实现跨语言调用:

Python端示例(用FastAPI搭建服务)

from fastapi import FastAPI

app = FastAPI()

# 假设你的Python制品提供的核心方法
def calculate_sum(a, b):
    return a + b

@app.get("/sum")
def api_sum(a: int, b: int):
    return {"result": calculate_sum(a, b)}

Spring Boot端调用示例

import org.springframework.web.client.RestTemplate;
import org.springframework.stereotype.Component;

@Component
public class PythonServiceClient {
    private final RestTemplate restTemplate;

    public PythonServiceClient(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    public Integer callSum(int a, int b) {
        String apiUrl = "http://localhost:8000/sum?a=" + a + "&b=" + b;
        return restTemplate.getForObject(apiUrl, Integer.class);
    }
}

方案2:使用Jython(进程内调用,仅兼容Python 2.x)

如果需要在Java进程内直接调用,可使用Jython(Java实现的Python解释器):

  1. 先在pom.xml添加依赖:
<dependency>
    <groupId>org.python</groupId>
    <artifactId>jython-standalone</artifactId>
    <version>2.7.3</version>
</dependency>
  1. Java调用代码示例:
import org.python.util.PythonInterpreter;

public class PythonMethodCaller {
    public static void main(String[] args) {
        try (PythonInterpreter interpreter = new PythonInterpreter()) {
            // 将.m2中Python制品的路径添加到Python搜索路径
            interpreter.exec("import sys");
            interpreter.exec("sys.path.append('/Users/yourname/.m2/repository/com/your/python/artifact/1.0.0')");
            interpreter.exec("from your_python_module import calculate_sum");
            
            // 调用方法并获取结果
            interpreter.exec("res = calculate_sum(3,5)");
            int result = interpreter.get("res", Integer.class);
            System.out.println("调用结果:" + result);
        }
    }
}

注意:Jython仅支持Python 2.x语法,若你的Python制品基于3.x开发,此方案不适用。

方案3:通过ProcessBuilder执行Python脚本

启动独立Python进程执行脚本,读取输出结果:

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

public class PythonScriptExecutor {
    public static String runPythonScript(String scriptPath, int param1, int param2) throws Exception {
        ProcessBuilder pb = new ProcessBuilder("python3", scriptPath, String.valueOf(param1), String.valueOf(param2));
        Process process = pb.start();
        
        BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        StringBuilder output = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            output.append(line);
        }
        
        int exitCode = process.waitFor();
        if (exitCode != 0) {
            throw new RuntimeException("Python脚本执行失败,退出码:" + exitCode);
        }
        return output.toString();
    }
}

需要先把Python制品的方法封装成可接收命令行参数的脚本,再通过上述代码调用。

关键注意点

  • 若Maven下载的是wheel/egg格式的Python包,需先解压后才能被Python解释器识别
  • 优先选择HTTP服务方案,跨语言耦合度最低,后续维护和扩展更方便

内容的提问来源于stack exchange,提问作者Dev Skelton

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 20:01:22