java中调用python的方法

今天折腾了下java中调用python的方法,上午在高手的指点下了个jar包,地址如下:http://sourceforge.net/projects/jpype/     在cmd下用java  jar  jython_installer-2.5.2   会生成一个目录,里面会有一个jar文件和其他的目录,跟python有点相似,在eclipse下面把这个jar文件添加进去,然后下代码调用python,具体如下:

package test;

import java.io.FileInputStream;
import java.io.InputStream;
import org.python.core.Py;
import org.python.util.PythonInterpreter;
import org.python.core.PySystemState;


public class Jpython_exec{
public static void main(String[] args) throws  Exception{
PythonInterpreter interpreter=new  PythonInterpreter();
// PySystemState sys = Py.getSystemState();
interpreter.exec("print 'hello'");
interpreter.exec("import  sys");
interpreter.exec("print sys.path");
interpreter.exec("for x  in xrange(10):print x \n");
// interpreter.execfile("D:\\Users\\zhoumeixu204\\Desktop\\test.py");  
// InputStream filepy = new FileInputStream("D:\\Users\\zhoumeixu204\\Desktop\\test.py"); 
}

}

//显示成功,但是执行interpreter.execfile("D:\\Users\\zhoumeixu204\\Desktop\\test.py");  时候报错,原因是我在test里面装了第三方库,Jpython识别不了,在网上//折腾一段时间没解决,后来用另外一种办法完美解决,如果有高手知道用这种办法,可以联系我,见代码如下:
package test;


import java.io.BufferedReader;
import java.io.InputStreamReader;

public class Jpython_pyhon_file {
        public static void main(String[] args){
                try{
                        System.out.println("start");
                        Process pr = Runtime.getRuntime().exec("python  D:\\Users\\zhoumeixu204\\Desktop\\test.py");
                        
                        BufferedReader in = new BufferedReader(new
                                InputStreamReader(pr.getInputStream()));
                        String line;
                        while ((line = in.readLine()) != null) {
                            System.out.println(line);
                        }
                        in.close();
                        pr.waitFor();
                        System.out.println("end");
                } catch (Exception e){
                            e.printStackTrace();
                        }
                }
}

能在后面执行代码,因为用python做数据清洗比较方便,包括图形识别,机器学习等能快速实现,再用java调,这样会方便很多

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值