java调用python

在java中直接执行python语句

添加maven依赖

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

Jython 是一种完整的语言,而不是一个 Java 翻译器或仅仅是一个 Python 编译器,它是一个 Python 语言在 Java 中的完全实现。 Jython 也有很多从 CPython 中继承的模块库。最有趣的事情是 Jython 不像 CPython 或其他任何高级语言,它提供了对其实现语言的一切存取。所以 Jython 不仅给你提供了 Python 的库,同时也提供了所有的 Java 类。这使其有一个巨大的资源库。

public class JavaRunPython {

  public static void main(String[] args) {
    PythonInterpreter interpreter = new PythonInterpreter();
    interpreter.exec("a='hello world'; ");
    interpreter.exec("print(len(a));"); // 11
  }

}

在java中执行python脚本

脚本内容

def my_sum(a,b):
  return a + b

print(my_sum(5,8))

java调用

public class JavaRunPython2 {

  public static void main(String[] args) throws FileNotFoundException {
    InputStream is = new FileInputStream("D:/pyutil.py");
    PythonInterpreter interpreter = new PythonInterpreter();
    interpreter.execfile(is);
  }

}

通过Runtime调用python脚本

public class RuntimeFunction {

  public static void main(String[] args) throws Exception {
    //具体的python安装路径
    String pythonPath = "C:\\Users\\xxx\\AppData\\Local\\Programs\\Python\\Python38\\python";
    Process proc = new ProcessBuilder().command(Arrays
        .asList(pythonPath, "D:\\pyutil.py")).start();
    BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
    String line = null;
    while ((line = in.readLine()) != null) {
      System.out.println(line);
    }
    in.close();
    proc.waitFor();
  }
}

总结

虽然在Java中调用Python可以有多种方式解决,甚至因为Jython的出现更显得非常便利。但是这种程序间嵌套调用的方式不可取,首先抛开调用性能不说,增加了耦合复杂度。更加有效的方式应该是通过RCP或者RESTful接口进行解耦,这样各司其职,也便于扩展,良好的架构是一个项目能够健康发展的基础。在微服务架构大行其道的今天,这种程序间嵌套调用的方式将会逐渐被淘汰。

posted @ 2020-10-18 16:25  strongmore  阅读(412)  评论(0编辑  收藏  举报