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();
      }
}

猜你喜欢

转载自blog.csdn.net/sinat_34241861/article/details/119779396