java如何调用python

Java 调用 Python 代码的方法:使用 Java Native Interface (JNI):加载 Python 解释器、获取引用、执行代码、获取结果。使用 Python for Java (Jython):导入库、创建解释器、执行代码、获取结果。

如何在 Java 中调用 Python

Java 和 Python 是两种流行的编程语言,有时需要在同一个应用程序中使用它们。Java 可以调用 Python 代码,从而实现不同语言之间的无缝协作。

方法:

有两种主要方法可以在 Java 中调用 Python 代码:

  • 使用 Java Native Interface (JNI): JNI 是一种低级接口,允许 Java 代码与本地代码(如 C/C++)交互。借助 JNI,我们可以从 Java 调用 Python 解释器。
  • 使用 Python for Java (Jython): Jython 是一个 Java 实现的 Python 解释器,它允许我们直接从 Java 代码中执行 Python 代码。

使用 JNI 调用 Python:

  1. 加载 Python 解释器:使用 System.loadLibrary 加载 Python 解释器的动态链接库 (DLL) 或共享对象 (SO)。
  2. 获取 Python 解释器引用:通过 JNI 函数找到 Python 解释器的引用。
  3. 执行 Python 代码:使用 JNI

    函数在解释器上执行 Python 代码。
  4. 获取结果:使用 JNI 函数从解释器中获取执行结果。

示例(使用 JNI):

import com.sun.jna.Library;
import com.sun.jna.Native;
import com.sun.jna.Pointer;
import com.sun.jna.ptr.IntByReference;

public class PythonCall {

    public static void main(String[] args) {
        // 加载 Python 解释器
        System.loadLibrary("python");

        // 获取 Python 解释器引用
        Pointer pyPtr = Python.INSTANCE.Py_Initialize();

        // 执行 Python 代码
        String code = "print('Hello from Python!')";
        Python.INSTANCE.PyRun_SimpleString(code);

        // 释放 Python 解释器
        Python.INSTANCE.Py_Finalize();
    }

    // JNI 接口
    public interface Python extends Library {
        Python INSTANCE = (Python) Native.loadLibrary("python", Python.class);

        Pointer Py_Initialize();
        Pointer Py_Finalize();
        void PyRun_SimpleString(String code);
    }
}

使用 Jython 调用 Python:

  1. 导入 Jython 库:导入 org.python.util.PythonInterpreter 类。
  2. 创建一个 Python 解释器:创建 PythonInterpreter 实例。
  3. 执行 Python 代码:使用 eval 方法在解释器上执行 Python 代码。
  4. 获取结果:从解释器中获取执行结果。

示例(使用 Jython):

import org.python.util.PythonInterpreter;

public class JythonCall {

    public static void main(String[] args) {
        // 创建 Python 解释器
        PythonInterpreter interpreter = new PythonInterpreter();

        // 执行 Python 代码
        interpreter.exec("print('Hello from Python!')");
    }
}