java调用python的几种方法整理

一、在java类中直接执行python语句

import org.python.util.PythonInterpreter;
public class FirstJavaScript {
    public static void main(String args[]) {
        PythonInterpreter interpreter = new PythonInterpreter();
        interpreter.exec("days=('mod','Tue','Wed','Thu','Fri','Sat','Sun'); ");
        interpreter.exec("print days[1];");
    }// main
}
调用的结果是Tue,在控制台显示出来,这是直接进行调用的。

二、在java中调用本机python脚本中的函数

import org.python.core.PyFunction;
import org.python.core.PyInteger;
import org.python.core.PyObject;
import org.python.util.PythonInterpreter;
 
public class FirstJavaScript {
    public static void main(String args[]) {
 
        PythonInterpreter interpreter = new PythonInterpreter();
        interpreter.execfile("C:\\Python27\\programs\\my_utils.py");
        PyFunction func = (PyFunction) interpreter.get("adder",
                PyFunction.class);
 
        int a = 2010, b = 2;
        PyObject pyobj = func.__call__(new PyInteger(a), new PyInteger(b));
        System.out.println("anwser = " + pyobj.toString());
    }// main
}
得到的结果是:anwser = 2012

三、使用java直接执行python脚本

import org.python.util.PythonInterpreter;
 
public class FirstJavaScript {
    public static void main(String args[]) {
 
        PythonInterpreter interpreter = new PythonInterpreter();
        interpreter.execfile("C:\\Python27\\programs\\input.py");
    }// main
}
四:如若python文件中有引入第三方库如numpy,sklearn,pandas等,可以通过java调用进程的方式

基本思路:通过java调用cmd,传入Python 命令,然后传入参数,通过获取到Python文件中的print,获取返回值

使用方式,将数据txt文件路径通过参数形式,传给Python且运行读取数据,最后java获取python的print的数据。

public static void main(String args[]){
        try{
            System.out.println("start");
                    String[] pythonData =new String[]{"python 运行的命令","py文件路径","测试传参数据文件路径"};
            //读取到python文件
            Process pr = Runtime.getRuntime().exec(pythonData);
            InputStreamReader ir = new InputStreamReader(pr.getInputStream());
            LineNumberReader in = new LineNumberReader(ir);
            String line ;
            //获取到python中的所有print 数据,
            while((line=in.readLine()) != null){
                System.out.println("python print data"+line);
            }
            ir.close();
            in.close();
            pr.waitFor();
            System.out.println("end");
        }catch(Exception e){
            e.printStackTrace();
        }

--------------------- 
作者:CWS_chen 
来源:CSDN 
原文:https://blog.csdn.net/secondlieutenant/article/details/79000265 
版权声明:本文为博主原创文章,转载请附上博文链接!

猜你喜欢

转载自blog.csdn.net/weixin_42587745/article/details/88408030