当前位置: 首页 > 技术教程

如何在Java中执行Python代码 java怎么调用python代码

  在Java项目中调用Python代码有多种方法,包括使用Jython、ProcessBuilder、Java Scripting API和JNI。每种方法都有其适用场景和优缺点。小编将详细介绍这些方法,并提供示例代码。

  1. 使用Jython

  Jython是一个由Java编写的Python解释器,允许在Java环境中运行Python代码。Jython作为Python在Java中的完整实现,提供了对Python库和Java类的访问,具有丰富的资源库。

  步骤:

  添加依赖:在Maven项目中添加Jython依赖。

  <dependency>

  <groupId>org.python</groupId>

  <artifactId>jython-standalone</artifactId>

  <version>2.7.0</version>

  </dependency>

  执行Python代码:使用PythonInterpreter类执行Python代码。

  import org.python.util.PythonInterpreter;

  import org.python.core.*;

  public class InvokePython {

  public static void main(String[] args) {

  PythonInterpreter pythonInterpreter = new PythonInterpreter();

  pythonInterpreter.exec("a='aaa'");

  pythonInterpreter.exec("print(a)");

  }

  }

  运行

  调用Python函数:加载Python脚本文件并调用其中的函数。

  import org.python.util.PythonInterpreter;

  import org.python.core.*;

  public class CallPythonFunction {

  public static void main(String[] args) {

  PythonInterpreter interpreter = new PythonInterpreter();

  interpreter.execfile("D:/Workspaces/J2EE/Test/config/my_utils.py");

  PyFunction func = (PyFunction) interpreter.get("adder", PyFunction.class);

  int a = 2010, b = 6;

  PyObject pyobj = func._call_(new PyInteger(a), new PyInteger(b));

  System.out.println("answer = " + pyobj.toString());

  }

  }

  运行

  注意事项:

  Jython支持的Python版本为2.7,不支持Python 3.x。

  Jython不再积极开发,可能不支持最新的Python库。

数据安全16.png

  2. 使用ProcessBuilder

  ProcessBuilder用于启动和管理操作系统进程,可以从Java中运行外部Python脚本并捕获输出。

  步骤:

  编写Python脚本:创建一个Python脚本文件input.py 。

  # open files

  print('hello')

  number = [3, 5, 2, 0, 6]

  print(number)

  number.sort()

  print(number)

  number.append(0)

  print(number)

  print(number.count(0))

  print(number.index(5))

  运行

  使用ProcessBuilder调用Python脚本:

  import java.io.BufferedReader;

  import java.io.InputStreamReader;

  public class TestPython {

  public static void main(String[] args) throws Exception {

  ProcessBuilder pb = new ProcessBuilder("python", "D:/Workspaces/J2EE/Test/config/input.py");

  Process process = pb.start();

  BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));

  String line;

  while ((line = reader.readLine()) != null) {

  System.out.println(line);

  }

  int exitCode = process.waitFor();

  System.out.println("Exited with error code : " + exitCode);

  }

  }

  运行

  优点:

  可以使用Python的所有库和模块。

  支持最新版本的Python。

  缺点:

  代码相对复杂,可读性较差。

  需要处理进程的输入输出流。

  3. 使用Java Scripting API

  Java Scripting API(JSR 223)允许Java通过统一接口调用各种脚本语言,包括Python。

  步骤:

  添加依赖:确保项目中包含javax.script包。

  使用ScriptEngineManager和ScriptEngine执行Python代码:import javax.script.ScriptEngine;

  import javax.script.ScriptEngineManager;

  import javax.script.ScriptException;

  public class ScriptEngineExample {

  public static void main(String[] args) {

  ScriptEngineManager manager = new ScriptEngineManager();

  ScriptEngine engine = manager.getEngineByName("python");

  try {

  engine.eval("print('Hello from Python!')");

  } catch (ScriptException e) {

  e.printStackTrace();

  }

  }

  }

  运行

  优点:

  提供统一接口调用多种脚本语言。

  简化了脚本语言的集成。

  缺点:

  需要额外的配置和依赖。

  性能可能不如直接使用Jython或ProcessBuilder。

  4. 使用JNI(Java Native Interface)

  JNI使Java代码能与C/C++编写的代码交互,从而间接调用Python代码。

  步骤:

  编写C/C++代码:创建一个C/C++函数调用Python代码。

  使用JNI调用C/C++函数:public class JNITest {

  static {

  System.loadLibrary("mylib");

  }

  private native void callPython();

  public static void main(String[] args) {

  new JNITest().callPython();

  }

  }

  运行

  优点:

  可以与C/C++代码交互。

  支持复杂的系统级操作。

  缺点:

  需要编写和编译C/C++代码。

  增加了项目的复杂性。

  在选择如何在Java中调用Python代码时,应根据具体需求和项目特点进行权衡。Jython适合频繁调用Python代码的场景,ProcessBuilder适用于简单脚本调用,Java Scripting API提供统一接口调用脚本语言,JNI适用于与C/C++代码交互。根据实际需求选择合适的方法,可以有效提升开发效率和代码的可维护性。

 


猜你喜欢