Java调用Python脚本

Jython主页:http://www.jython.org/

Jython是Python语言在Java平台的实现,本质上,Jython是由Java编写,其是在JVM上实现的Python语言。因此,可以直接通过Jython在Java中调用Python。

引入jython依赖

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

Example

    public static void main(String[] args) {
        PythonInterpreter interpreter = new PythonInterpreter();
        //执行python
        interpreter.exec("print (10086)");
    }

Run Python File demo.py

        // init PythonInterpreter
        PythonInterpreter interpreter = new PythonInterpreter();
        // catch File Exception
        try{
            InputStream filepy = new FileInputStream("D:xxx.py");
            // run python file
            interpreter.execfile(filepy);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            interpreter.close();
        }

获取函数名

//获取函数名test

PyFunction pyf = inter.get("test", PyFunction.class);

//向函数中传递参数并获取返回结果

PyObject res = pyf.__call__(Py.newInteger(2), Py.newInteger(3));

System.out.print(res);

inter.cleanup();

inter.close();

 

posted @ 2022-05-17 15:47  沾青先生  阅读(298)  评论(0编辑  收藏  举报