一、在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();
		}
	}

内容来源于网络

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐