java调用python脚本

背景

在开发一个项目的某个功能的时候,需要要用一个算法模型(甲方已提供python脚本),但后端用是java来写的。开始想用java来重写,但因为涉及到某些库,java不怎么支持。后来没办法,就尝试用java来调用python脚本。结果没想到还真可以。

引入版本

           <!--调用python使用-->
        <dependency>
            <groupId>org.python</groupId>
            <artifactId>jython-standalone</artifactId>
            <version>2.7.0</version>
        </dependency>
        
       

核心调用方法

#脚本我放在了config文件夹下,可以灵活更改脚本内容。
	 public static String resolvePythonScriptPath(String filename) {
        File file = new File("./config/" + filename);
        return file.getAbsolutePath();
    }

    public static List<String> readProcessOutput(InputStream inputStream) throws IOException {
        try (BufferedReader output = new BufferedReader(new InputStreamReader(inputStream))) {
            return output.lines()
                    .collect(Collectors.toList());
        }
    }




python脚本

因为涉及到甲方的隐私,我就随便写了给脚本。

##!/usr/bin/python
# -*- coding: utf-8 -*-
if __name__ == "__main__":
    print(1+2)

调用案例

 
        public static void main(String[] args) throws IOException {
        ProcessBuilder processBuilder = new ProcessBuilder("python",
                resolvePythonScriptPath("algorithm.py"));
        processBuilder.redirectErrorStream(true);

        Process process = processBuilder.start();
        List<String> results = readProcessOutput(process.getInputStream());
        System.out.println("results = " + results);
    }

成功截图

在这里插入图片描述

学习java群

java交流群:868794080

源码下载链接

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一枚开发小咸鱼

原创不宜,请作者喝杯咖啡吧。

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值