Java中使用Python脚本及动态传参的方法

一、背景介绍

在实际工作中需要使用JsonSchema解析json数据,JsonSchema中的新功能if-then-else在Java中无法生效,但是Python脚本就可以(咱也不知道为什么)。于是自己便生出一个想法,是否可以在Java中执行Python脚本呢?百度一番还真有这种操作

pom.xml文件中需要引入相应的依赖包

<dependency>
     <groupId>org.python</groupId>
     <artifactId>jython-standalone</artifactId>
     <version>2.7.0</version>
</dependency>

二、使用Python的四种方法

2.1 在Java类中直接执行Python语句

@Test
public void test1(){
    PythonInterpreter interpreter = new PythonInterpreter();
    interpreter.exec("a='hello world'; ");
    interpreter.exec("print a;");
}

2.2 在Java中直接调用Python脚本

@Test
public void test2(){
    PythonInterpreter interpreter = new PythonInterpreter();
    interpreter.execfile("/Users/sundongping/python/JsonSchema7ForApiCase.py");
 }

2.3 使用Runtime.getRuntime()执行Python脚本文件,推荐使用

    @Test
    public void test3(){
        Process proc;
        String pythonPath = "/Users/xxxx/python/JsonSchema7ForApiCase.py";
        try {
            String[] strings = {"python3", pythonPath};
            proc = Runtime.getRuntime().exec(strings);
            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();
        }
    }

2.4 调用Python脚本中的函数

@Test
public void test4(){
    PythonInterpreter interpreter = new PythonInterpreter();
    interpreter.execfile("/Users/xxxx/python/JsonSchema7ForApiCase.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);
}

三、Java中实现Python脚本的动态传参

@Test
public void test5(){
     String inputStr2 = "{\n" +
            "    \"type\":\"object\",\n" +
            "    \"properties\":{\n" +
            "        \"presp\":{\n" +
            "            \"type\":\"object\",\n" +
            "            \"properties\":{\n" +
            "                \"pdata\":{\n" +
            "                    \"type\":\"object\",\n" +
            "                    \"properties\":{\n" +
            "                        \"flightBusyInfo\":{\n" +
            "                            \"type\":\"object\"\n" +
            "                        },\n" +
            "                        \"flightInfo\":{\n" +
            "                            \"type\":\"array\"\n" +
            "                        }\n" +
            "                    }\n" +
            "                }\n" +
            "            },\n" +
            "            \"if\":{\n" +
            "                \"properties\":{\n" +
            "                    \"pdata\":{\n" +
            "                    \"type\":\"string\",\n" +
            "                        \"minProperties\":1\n" +
            "                    }\n" +
            "                }\n" +
            "            },\n" +
            "            \"then\":{\n" +
            "                \"required\":[\n" +
            "                    \"pdata\"\n" +
            "                ]\n" +
            "            },\n" +
            "            \"else\":{\n" +
            "                \"properties\":{\n" +
            "                    \"pdata\":{\n" +
            "                        \"minProperties\":1\n" +
            "                    }\n" +
            "                }\n" +
            "            }\n" +
            "        }\n" +
            "    }\n" +
            "}";
    String data2 = "{\"pkey\":\"2021-08-17 17:29:58\",\"pname\":\"\",\"ppid\":\"1060030\",\"presp\":{\"hinttype\":0,\"pdata\":{},\"perrcode\":0},\"pret\":1,\"pver\":\"\"}";
    
    try {
          //设置命令行传入参数
          String[] args = new String[] { "python3", "/Users/sundongping/python/test.py", inputStr2, data2};
          Process pr = Runtime.getRuntime().exec(args);

          BufferedReader in = new BufferedReader(new InputStreamReader(pr.getInputStream()));
          String line;
          while ((line = in.readLine()) != null) {
              System.out.println(line);
          }
          in.close();
          pr.waitFor();
      } catch (Exception e) {
          e.printStackTrace();
      }
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值