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

内容来源于网络

  • 3
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值