日期:2014-05-18  浏览次数:20765 次

eclipse中 java程序怎样调用python?
小女子要做一个项目是基于lucene3.0的中文搜索引擎,建立索引的时候不用lucene自带的分词系统,想用已经编写完的用python语言编写的分词系统。。

怎样才能从java程序中调用已经编写完的python文件呢?

各位高手帮帮小女子吧~~

谢谢了~~

(补充:开发环境是 win7 , eclipse !!)
lucene?java?python? lucene java python

------解决方案--------------------
比较简单的是用exec去直接执行.py文件
public static void main(String[] args) throws IOException {
// set up the command and parameter
String pythonScriptPath = "/home/norbert/python/helloPython.py";
String[] cmd = new String[2];
cmd[0] = "python2.6";
cmd[1] = pythonScriptPath;
// create runtime to execute external command
Runtime rt = Runtime.getRuntime();
Process pr = rt.exec(cmd);
// retrieve output from python script
BufferedReader bfr = new BufferedReader(new InputStreamReader(pr.getInputStream()));
String line = "";
while((line = bfr.readLine()) != null) {
// display each output line form python script
System.out.println(line);
}
}
python部分扩展包不多的话可以考虑jython,目前这种方式比较推荐,但是jython和python有一定的兼容性问题
还可以用JNI,cython,通过java调C,C调python实现