java中调用python的几种方式(记录)

第一种:通过runtime

Runtime runtime = Runtime.getRuntime();

try {

Process process = runtime.exec("python3 /home/liudong/Documents/BPANN/test.py");

}catch (IOException e) {

e.printStackTrace();

}

第二种:通过jython(不传递参数,不依赖第三方模块)

PythonInterpreter interpreter =new PythonInterpreter();

        interpreter.exec("print('hello')");//执行Python代码

        interpreter.execfile("/home/liudong/Documents/BPANN/test.py");//执行python文件

第三种:调用需要传入参数的Python文件

        PythonInterpreter interpreter =new PythonInterpreter();

        interpreter.execfile("/home/liudong/Documents/BPANN/test.py");//要执行python文件

        PyFunction function = interpreter.get("aa", PyFunction.class);//得到Python文件中的函数

        //new PyString()代表传入的参数

        PyObject pyObject = function.__call__(new PyString("jiajiajaijai"), new PyString("ddddddd"));

        System.out.println("answer:: " + pyObject.toString());

对应的python文件为:

    def aa(name, sex):

        print("name: " + name)

        print("sex: " + sex)

        return name + sex

第四种:如何处理依赖了第三方模块的Python文件

本地文件下载相应的包,否则会一直报没有名为什么的模块。

通过命令行执行相应的命令(可以传递参数),可以通过输入流获取相应的结果,从而进行下一步操作。

模板代码如下:

Runtime runtime = Runtime.getRuntime();

try {

Process process = runtime.exec("python3.5 /home/liudong/PycharmProjects/bpann/webBPANN_interface.py");

    InputStream inputStream = process.getInputStream();

    BufferedReader bufferedReader =new BufferedReader(new InputStreamReader(inputStream));

    String line;

    StringBuilder stringBuilder =new StringBuilder();

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

System.out.println(line);

        stringBuilder.append(line);

    }

System.out.println(stringBuilder.toString());

    System.out.println(process.waitFor());

}catch (Exception e) {

e.printStackTrace();

}

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Python 面向对象Python从设计之初就已经是一门面向对象的语言,正因为如此,在Python中创建一个类和对...
    顺毛阅读 4,239评论 4 16
  • 废话不多说,自己进入今天的主题 1、面向对象的特征有哪些方面? 答:面向对象的特征主要有以下几个方面: - 抽象:...
    传奇内服号阅读 2,402评论 1 31
  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 31,767评论 18 399
  • 0:00 A: "OK, so the game's going to start now, mom" 0:02 ...
    LunarShade阅读 331评论 0 0
  • 有一个美丽的地方 人们都把它向往 有一个美丽的地方 传说是神仙居住的地方 这里就是乡巴拉———乡城 2014年6...
    德可儿吉阅读 213评论 4 2