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

Java调用Python开发环境配置(Eclipse+Jython+PyDev)

2016-03-09 14:36 726 查看

Java调用Python开发环境配置(Eclipse+Jython+PyDev)

环境配置

安装好eclipse,JDK ,略过。

下载Jython,http://www.jython.org/,解压出来如下



配置jython到Path,如下,Path=D:\Program Files (x86)\jython2.7.0\bin,注意要到bin目录



下载PyDev插件(eclipse下用来开发python的插件)

eclipse中通过插件安装方式自动下载,

https://dl.bintray.com/fabioz/pydev/4.5.4/(网上说的老地址已经失效了 )



安装完后在eclipse-window-Preferences-PyDev-Jython Interpreter中添加jython.jar,如下图



以下2步Python 3.x必选,Python 2随意。

General->Editors->Text Editors->Spelling,Encoding改成Other:UTF-8

General->Workspace,Text file encoding改成Other:UTF-8

代码编写

新建一个普通java项目,把jython.jar加入到项目依赖的jar包里,在java项目里创建一个py文件,编写python代码。如下

from java.util import ArrayList
a= ArrayList();
a.add(1);
a.add(2);
a.add(3);
a.add(4);
print (a);


这里的from java.util import ArrayList是使用java的ArrayList类。

再创建一个带main方法的java类。如下

public static void main(String[] args) {
Properties props = new Properties();
//      props.put("python.home","path to the Lib folder");
props.put("python.console.encoding", "UTF-8"); // Used to prevent: console: Failed to install '': java.nio.charset.UnsupportedCharsetException: cp0.
props.put("python.security.respectJavaAccessibility", "false"); //don't respect java accessibility, so that we can access protected members on subclasses
props.put("python.import.site","false");
Properties preprops = System.getProperties();

PythonInterpreter.initialize(preprops, props, new String[0]);
PythonInterpreter interp = new PythonInterpreter();
interp.execfile("F:\\workspace\\wxserver\\WebContent\\py\\test.py");
}


按F9执行main方法,在控制台输出[1, 2, 3, 4]。

Properties中设置的几个参数是为了避免出现如下图的

console: Failed to install ”: java.nio.charset.UnsupportedCharsetException: cp0和ImportError: Cannot import site module and its dependencies: No module named site等错误

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: