java调用python代码

同样的我们需要安装jython,具体的步骤如下:

1. 去 http://sourceforge.net/projects/jython/ 下载最新的jython相关的jar包。

2. 下载下来的jar包其实既是使用的时候需要引入的jar包,也是安装就jython的jar包。具体安装细节参照:https://wiki.python.org/jython/InstallationInstructions#jython-2-7-0

其实直接使用: java -jar jython_installer-2.5.2.jar 就可以根据界面指导进行安装。

3. 如果我们现在想在java中调用python代码或者执行python文件,我们只需引入jypthon安装目录下的jython.jar即可。(这一点和jruby的使用方式类似)

 

调用的代码示例如下:

1 PythonInterpreter interpreter = new PythonInterpreter();  
2 interpreter.exec("days=('mod','Tue','Wed','Thu','Fri','Sat','Sun'); ");  
3 interpreter.exec("print days[1];"); 
JavaCallPython

首次调用会输出很多标红的编译对应jar包的信息:

 1 *sys-package-mgr*: processing new jar, '/home/zyq/KiDe/Redis/jar4java/commons-pool-1.5.4.jar'
 2 *sys-package-mgr*: processing new jar, '/home/zyq/KiDe/Redis/jar4java/jedis-2.1.0.jar'
 3 *sys-package-mgr*: processing new jar, '/home/zyq/KiDe/Redis/jar4java/junit-4.8.2.jar'
 4 *sys-package-mgr*: processing new jar, '/opt/jruby/jruby-9.1.2.0/lib/jruby.jar'
 5 *sys-package-mgr*: processing new jar, '/home/zyq/jython2.5.2/jython.jar'
 6 *sys-package-mgr*: processing new jar, '/opt/java/jdk1.8.0_91/jre/lib/resources.jar'
 7 *sys-package-mgr*: processing new jar, '/opt/java/jdk1.8.0_91/jre/lib/rt.jar'
 8 *sys-package-mgr*: processing new jar, '/opt/java/jdk1.8.0_91/jre/lib/jsse.jar'
 9 *sys-package-mgr*: processing new jar, '/opt/java/jdk1.8.0_91/jre/lib/jce.jar'
10 *sys-package-mgr*: processing new jar, '/opt/java/jdk1.8.0_91/jre/lib/charsets.jar'
11 *sys-package-mgr*: processing new jar, '/opt/java/jdk1.8.0_91/jre/lib/jfr.jar'
12 *sys-package-mgr*: processing new jar, '/opt/java/jdk1.8.0_91/jre/lib/ext/sunpkcs11.jar'
13 *sys-package-mgr*: processing new jar, '/opt/java/jdk1.8.0_91/jre/lib/ext/jfxrt.jar'
14 *sys-package-mgr*: processing new jar, '/opt/java/jdk1.8.0_91/jre/lib/ext/cldrdata.jar'
15 *sys-package-mgr*: processing new jar, '/opt/java/jdk1.8.0_91/jre/lib/ext/sunjce_provider.jar'
16 *sys-package-mgr*: processing new jar, '/opt/java/jdk1.8.0_91/jre/lib/ext/zipfs.jar'
17 *sys-package-mgr*: processing new jar, '/opt/java/jdk1.8.0_91/jre/lib/ext/localedata.jar'
18 *sys-package-mgr*: processing new jar, '/opt/java/jdk1.8.0_91/jre/lib/ext/nashorn.jar'
19 *sys-package-mgr*: processing new jar, '/opt/java/jdk1.8.0_91/jre/lib/ext/jaccess.jar'
20 *sys-package-mgr*: processing new jar, '/opt/java/jdk1.8.0_91/jre/lib/ext/sunec.jar'
21 *sys-package-mgr*: processing new jar, '/opt/java/jdk1.8.0_91/jre/lib/ext/dnsns.jar'
FirstInvokeInfo

后续调用的结果如下:

1 Tue
Result

 

posted @ 2016-08-22 12:04  Secondworld  阅读(1182)  评论(0编辑  收藏  举报