zoukankan      html  css  js  c++  java
  • 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接口进行解耦,这样各司其职,也便于扩展,良好的架构是一个项目能够健康发展的基础。在微服务架构大行其道的今天,这种程序间嵌套调用的方式将会逐渐被淘汰。

  • 相关阅读:
    mysql workbench 建表时PK, NN, UQ, BIN, UN, ZF, AI
    Asan检测内存读越界
    C 实现 C++ 的面向对象特性(封装、继承、多态)
    VIBE算法
    Go 大坑 nil
    求二叉树中节点的最大距离
    计算[1,N]范围内含有7的数字的个数
    一组便于创建线程和线程池的简单封装函数
    用C#执行doc命令
    可以自由停靠的窗体!
  • 原文地址:https://www.cnblogs.com/strongmore/p/13835819.html
Copyright © 2011-2022 走看看