java调用python脚本 并传参(根据配置文件获取python文件地址)

方式一:
Java代码

package com.mybatis.plus.utils;
import cn.hutool.core.lang.Console;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class test1 {
    public static void main(String[] args) {

        String[] arguments = new String[] {"python", "D://test.py","9895656"};
        try {
            Process process = Runtime.getRuntime().exec(arguments);
            BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream(),
                    "GBK"));
            String line = null;
            while ((line = in.readLine()) != null) {
                System.out.println(line);
            }
            in.close();
            //java代码中的process.waitFor()返回值为0表示我们调用python脚本成功,
            //返回值为1表示调用python脚本失败,这和我们通常意义上见到的0与1定义正好相反
            int re = process.waitFor();
            System.out.println(re);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Python

from enum import Enum
import sys

class Solution:
    def reverse(self, x: int) -> int:
        if x==0:
            return 0
        strList = []
        isPositive = True
        if x < 0:
            isPositive = False
        value = abs(x)
        temp = value
        while (temp/10.0>0.09):
            i = temp%10
            strList.append(str(i))
            temp = temp//10
        join = "".join(strList)
        result = int(join)
        if result>2147483647:
            result=0
        if isPositive == False:
            result = -result
        return result

if __name__ == "__main__":
    so = Solution()
    print("输入参数:"+sys.argv[1])
    print(so.reverse(int(sys.argv[1])))


读取配置文件中的数据

Java代码

import com.mysql.cj.log.Log;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

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

@RestController
@PropertySource({"application.yml"})
@RequestMapping("/camera")
public class CameraController {
    @Value("${python.path}")
    private String python;
    @Value("${python.file}")
    private String pythonFile;
    @GetMapping("/")
    //TODO 修改application.yml中的python地址以及py文件的位置
    public Response move() {
        try {
            //使用String数组保存主要数据 参数一:使用什么平台 参数二:运行的程序位置 参数三:向所要运行的程序中传递参数多个参数写到参数四,参数...
            String[] args1 = new String[]{python, pythonFile, "9895656"};
            //使用Runtime.getRuntime().exec()使用指定程序运行指定程序
            Process pr = Runtime.getRuntime().exec(args1);
            //设置BufferedReader读取的编码格式
            BufferedReader in = new BufferedReader(new InputStreamReader(
                    pr.getInputStream(), "GBK"));
            String line;
            //循环读取行不为空输出
            while ((line = in.readLine()) != null) {
                System.out.println(line);
            }
            //关闭流
            in.close();
            pr.waitFor();
        } catch (Exception e) {
            e.printStackTrace();
            return Response.fail();
        }
        return Response.success();
    }


}

application.yml配置文件

转自:https://www.cnblogs.com/guanxiaohe/p/14172018.html

方式二:

此方法需要引入依赖

 <dependency>
       <groupId>org.python</groupId>
       <artifactId>jython-standalone</artifactId>
       <version>2.7.0</version>
 </dependency>
import org.junit.jupiter.api.Test;
import org.python.core.PyFunction;
import org.python.core.PyInteger;
import org.python.core.PyObject;
import org.python.util.PythonInterpreter;

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

class SamplerApplicationTests {
    @Test
    public void test() throws IOException {
        PythonInterpreter interpreter = new PythonInterpreter();
        interpreter.execfile("D:\\add1.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);
    }

}

python代码

def add(a,b):
    return a + b

参考自:https://www.cnblogs.com/wuwuyong/p/10600749.html

本文作者:努力的小韩

本文链接:https://www.cnblogs.com/HanYork/p/16896652.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   努力的小韩  阅读(1090)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起
  1. 1 雪下的时候 乔佳旭
雪下的时候 - 乔佳旭
00:00 / 00:00
An audio error has occurred.

作词 : 乔佳旭

作曲 : 乔佳旭

编曲:侯江浩

如果你有空 陪我过个冬

这话多像肆意的寒风

我不会感动 不会道保重

你有多想我无动于衷

我以为会不痛 学了几遍从容

无师自通 眼看匆匆

你曾说的心疼 曾深拥过的梦

我倒想问这算哪门子喜欢

雪下的时候 是想念的汹涌

雪停的时候 大概扑了空

你千万别念旧 别对我宽容

我多半会心动

雪下的刚好 提醒我抱不到

这白色的外表 多像在求饶

那冻裂的伤口 还需不需要

你医治好

我以为会不痛 学了几遍从容

无师自通 眼看匆匆

你曾说的心疼 曾深拥过的梦

我倒想问这算哪门子喜欢

雪下的时候 是想念的汹涌

雪停的时候 大概扑了空

你千万别念旧 别对我宽容

我多半会心动

雪下的刚好 提醒我抱不到

这白色的外表 多像在求饶

那冻裂的伤口 还需不需要

你医治好

雪下的时候 是想念的汹涌

雪停的时候 大概扑了空

你千万别念旧 别对我宽容

我多半会心动

雪下的刚好 提醒我抱不到

这白色的外表 多像在求饶

那冻裂的伤口 还需不需要

你医治好

吉他:吴海锋

混音:张栩赫(Ethan)

录音:觉醒爷爷(Kent)

和声编写/和声:觉醒爷爷(Kent)

配唱制作人/制作人:觉醒爷爷(Kent)

录音工作室: 1803 Music Studio

混音工作室:Hot Music Studio

企划营销:梦童娱乐

监制:三千

OP:千和世纪

(版权所有未经许可请勿使用)