java调用python汇总

pom引用


        
            org.python
            jython-installer
            2.7.3
        
        
            org.python
            jython-standalone
            2.7.3
        

java

package com.ty.utils;

import org.python.core.Py;
import org.python.core.PyFunction;
import org.python.core.PyInteger;
import org.python.core.PyObject;
import org.python.util.PythonInterpreter;

/**
 * @author huawangxin
 * @data 2023/5/25
 * @apiNote
 */
public class PythonUtils {
    public static void main(String[] args) {
        //在Java中执行Python语句
        //simplePythonAction();
        
        //在Java中简单调用Python程序,不需要传递参数,也不需要获取返回值
        //simplePythonFile();

        //在Java中单向调用Python程序中的方法,需要传递参数,并接收返回值。【项目用这个方法即满足条件】
        callBackPythonFile();

    }

    private static void callBackPythonFile() {
        System.setProperty("python.home", "D:\\Program\\jython2.7.3");

        // 1. Python面向函数式编程: 在Java中调用Python函数
        String pythonFunc = "D:\\calculator_func.py";

        PythonInterpreter pi1 = new PythonInterpreter();
        // 加载python程序
        pi1.execfile(pythonFunc);
        // 调用Python程序中的函数
        PyFunction pyf = pi1.get("power", PyFunction.class);
        PyObject dddRes = pyf.__call__(Py.newInteger(2), Py.newInteger(3));
        System.out.println(dddRes);
        pi1.cleanup();
        pi1.close();

        // 2. 面向对象式编程: 在Java中调用Python对象实例的方法
        String pythonClass = "D:\\calculator_clazz.py";
        // python对象名
        String pythonObjName = "cal";
        // python类名
        String pythonClazzName = "Calculator";
        PythonInterpreter pi2 = new PythonInterpreter();
        // 加载python程序
        pi2.execfile(pythonClass);
        // 实例化python对象
        pi2.exec(pythonObjName + "=" + pythonClazzName + "()");
        // 获取实例化的python对象
        PyObject pyObj = pi2.get(pythonObjName);
        // 调用python对象方法,传递参数并接收返回值
        PyObject result = pyObj.invoke("power", new PyObject[] {Py.newInteger(2), Py.newInteger(3)});
        double power = Py.py2double(result);
        System.out.println(power);

        pi2.cleanup();
        pi2.close();
    }

    private static void simplePythonAction() {
        System.setProperty("python.home", "D:\\Program\\jython2.7.3");
        PythonInterpreter interp = new PythonInterpreter();
        // 执行Python程序语句
        interp.exec("import sys");
        interp.set("a",new PyInteger(42));
        interp.exec("print a");
        interp.exec("x = 2+2");
        PyObject x = interp.get("x");
        System.out.println("x: " + x);
    }

    private static void simplePythonFile() {
        System.setProperty("python.home", "D:\\Program\\jython2.7.3");
        String python = "D:\\helloword.py";
        PythonInterpreter interp = new PythonInterpreter();
        interp.execfile(python);
        interp.cleanup();
        interp.close();
    }


}

你可能感兴趣的:(python,java,开发语言)