您的位置:首页 > 编程语言 > Python开发

Jython:java调用python文件之第三方包路径问题

2016-05-07 15:40 716 查看
本方法解决python代码的可移植性,不需要在新机器上配置python环境,只通过安装jython的方式将python代码嵌入java工程

1. Jython如何安装

下载地址:jython_installer-2.5.0.jar  。下载需要积分,如果无积分,可联系楼主。

傻瓜式下一步安装方式,路径最好和工程选在同一目录下。

2. 运行python代码

举个简单例子,安装好java环境及eclipse之后,copy如下代码即可运行。注释部分为运行文件的方式,需要新建文件后去掉注释执行。

import java.io.IOException;
import org.python.util.PythonInterpreter;
public class test {
public static void main(String args[]) throws IOException {
PythonInterpreter interpreter = new PythonInterpreter();
// 运行python语句
interpreter.exec("a = \"hello, Jython\"");
interpreter.exec("print a");
// 执行python文件
//  interpreter.exec("filepy = \"E:\\test.py\"");
//  interpreter.execfile(filepy);  ///执行python py文件
//  filepy.close();
}
}
3. 处理第三方包

在文件运行方式中,

第一种情况:如果.py文件中包含同一目录的自定义包,则在eclipse工程下可正常调用。

第二种情况:如果包含第三方包,需要拷贝到当前目录下。

第三种情况:由于路径问题无法调用。Jython/lib文件下有大量第三方包,如os, re, __future__,重复拷贝费时费力,这时可手动修改path路径。(推荐)

修改路径有两种方式:

(1) Java方式

import org.python.core.Py;
import org.python.core.PySystemState;
System.out.println(sys.path.toString());    // previous
PySystemState sys = Py.getSystemState();
sys.path.add("E:\\sacaapm-paserver\\src-python\\jython\\Lib");
System.out.println(sys.path.toString());   // later


将代码嵌入part 2代码,得到完整代码后执行,可以看到前后路径发生变化。

(2) python方式

interpreter.exec("import sys");
interpreter.exec("print sys.path");


(3) 灵活运用以上两种方式或其组合形式。

当import sys时报出“sys模块不存在”的错误,建议使用第一种。

完整代码如下:

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import org.python.core.Py;
import org.python.core.PySystemState;
import org.python.util.PythonInterpreter;

public class test {
public static void main(String args[]) throws IOException {
PythonInterpreter interpreter = new PythonInterpreter();
PySystemState sys = Py.getSystemState();
sys.path.add("E:\\src-python\\jython\\Lib");
interpreter.exec("import sys");
interpreter.exec("print sys.path");
interpreter.exec("path = \"E:\\src-python\\jython\\Lib\"");
interpreter.exec("sys.path.append(path)");
interpreter.exec("print sys.path");
interpreter.exec("a=3; b=5;");
InputStream filepy = new FileInputStream("E:\\input.py");
interpreter.execfile(filepy);
filepy.close();
}
}



运行结果:
['E:\\lib\\Lib', '__classpath__', '__pyclasspath__/', u'E:\\src-python\\jython\\Lib']
['E:\\lib\\Lib', '__classpath__', '__pyclasspath__/', u'E:\\src-python\\jython\\Lib', 'E:\\src-python\\jython\\Lib']
a/b= 0.6

E:\\input.py文件代码:

from __future__ import division
print "a/b=",a/b

其中变量a, b的值由java传入。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: