2021-12-19 02:27

java调用Python脚本

码自答

Python

(727)

(0)

收藏

一 通过Runtime执行

    通过Runtime.getRuntime()方法获得当前java运行环境,再将python脚本传入当前平台的Python环境执行该脚本.

    Python脚本程序.c:/userTest/Test.py

print("wanmait");

   java代码:

String str = "python c:/userTest/Test.py";
try {
    Process process = Runtime.getRuntime().exec(str);
    //获得当前java运行环境

    InputStream inputStream = process.getInputStream();
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
    //创建字符输入缓冲流

    String data = bufferedReader.readLine();
    //获得脚本运行输出的信息

    System.out.println(data);
    process.waitFor();
    bufferedReader.close();
    inputStream.close();
} catch (IOException e) {
    e.printStackTrace();
}

  运行结果:

image.png


二 通过jython执行

    下载jython库

    https://www.jython.org/download

    image.png

image.png

1 java不向Python传递实参,也不接收Python的返回值

   Python程序.c:/userTest/Test.py

print("wanmait");

  java程序:

PythonInterpreter pythonInterpreter = new PythonInterpreter();

pythonInterpreter.execfile("c:/userTest/Test.py");
//利用Python解析器解析Python程序

pythonInterpreter.close();

  执行结果:

  image.png


2 java向Python方法传递实参,并接收返回值

  Python程序,c:/userTest/Test.py

def add(arg1,arg2):
    return arg1+arg2;

java程序:

PythonInterpreter pythonInterpreter = new PythonInterpreter();

pythonInterpreter.execfile("c:/userTest/Test.py");
//利用Python解析器解析Python程序  加载Python文件

PyFunction pyFunctionAdd = pythonInterpreter.get("add", PyFunction.class);
//获得名称是add的Python方法

PyObject pyObject = pyFunctionAdd.__call__(Py.newInteger(2),Py.newInteger(3));
//执行add方法  pyOnject接收返回值 Py.newInteger()是PyInteger对象作为实参

System.out.println(pyObject);
pythonInterpreter.close();

程序执行结果:

image.png


3 java实例化Python类,并调用方法

Python程序,c:/userTest/Test.py

class Test:
    def add(self,arg1,arg2):
        return arg1+arg2;

Test类,add方法

Java程序

PythonInterpreter pythonInterpreter = new PythonInterpreter();

pythonInterpreter.execfile("c:/userTest/Test.py");
//利用Python解析器解析Python程序  加载Python文件

pythonInterpreter.exec("test=Test()" );
//实例化Pyhton的Test类  test是对象名  Test类名

PyObject pyObjectTest = pythonInterpreter.get("test");
//获得实例test

PyObject[] args = {Py.newInteger(2),Py.newInteger(3)};
PyObject pyObject = pyObjectTest.invoke("add",args);
//通过test对象调用add方法  PyObject数组作为add方法的实参
//pyObject接收add方法的返回值

System.out.println(pyObject);
pythonInterpreter.close();

执行结果:

image.png

0条评论

点击登录参与评论