【springboot+python】 尝试springboot调用python的demo

本文介绍了一个Java程序如何通过命令行调用Python脚本并获取返回结果的示例。该示例展示了如何设置参数、执行Python脚本及读取输出结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

只是一个尝试demo

python代码

import sys


def detect(path):
    print("python running:")
    return "python result:"+path


if __name__ == '__main__':
# 参数从argv的第二个元素开始,第一个元素是运行的程序名
    path = sys.argv[1]
    print(detect(path))

springboot的controller

@RestController
public class DetectController {

    @GetMapping
    public void  detect(HttpServletRequest request){
        String path = request.getAttribute("path").toString();

        try {
            // 一维数组,第二个参数是文件的路径,后面的是python代码的参数
            // 我猜是通过命令行指令?
            String[] args = new String[]{"python","D:\\pycharm_project\\test\\lungDetect\\detect.py",path};
            // 执行py文件
            Process process = Runtime.getRuntime().exec(args);
            // 获取输出的结果(打印在控制台的字符?)
            BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line = in.readLine();
            while(line!=null){
                // 显示结果
                System.out.println("springboot执行python结果:"+line);
                line = in.readLine();
            }
            in.close();
            process.waitFor();
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }


        System.out.println("controller任务已完成");
    }

}

springboot的测试用例

@SpringBootTest
class DetectControllerTest {
    DetectController detectController;


    @Autowired
    public void setDetectController(DetectController detectController) {
        this.detectController = detectController;
    }

    @Test
    void detect() {
        HttpServletRequest request = new MockHttpServletRequest();
        request.setAttribute("path","www.heguchangan.xyz");
        detectController.detect(request);
    }
}

结果

在这里插入图片描述

原理

猜想是java通过使用命令行执行执行python xxx.py,来执行python文件,然后将打印出来的结果读取到io中在打印出来。具体原理待学习。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值