免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 9345 | 回复: 0
打印 上一主题 下一主题

java中调用python程序 [复制链接]

论坛徽章:
4
天蝎座
日期:2013-11-06 11:39:34巳蛇
日期:2014-01-16 16:53:14午马
日期:2014-08-25 21:42:302015年迎新春徽章
日期:2015-03-03 17:21:44
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2007-12-08 16:14 |只看该作者 |倒序浏览
费了一天的时间,想用Jpython生成的jar文件在java中调用,没有行能,既然行不通,那就反过来吧,在java中直接调用python程序,呵呵,成功了,现在拿出来与大家分享

Jpython jython2.2.1
JDK 1.5

以下是程序代码
python.java


import java.util.List;

import org.python.core.PyException;
import org.python.core.PyInteger;
import org.python.core.PyObject;
import org.python.util.PythonInterpreter;
public class python {
        public static void main(String []args)throws PyException
        {
                PythonInterpreter interp =new PythonInterpreter();
               
                System.out.println("Hello, brave new world";
               
                interp.exec("import sys";
                interp.exec("print sys";
               
                interp.set("a", new PyInteger(42));
                interp.exec("print 'test='+str(a)";
                interp.exec("x = 2+2";
                PyObject x = interp.get("x";
               
                System.out.println("x: "+x);
                System.out.println("Goodbye, cruel world";
               
                interp.exec("import re";

                interp.exec("t =re.compile('^(0{2})IFCSUM)MANIFEST):')";
                interp.exec(" a = t.search('00:IFCSUM:MANIFEST:').groups()";
                PyObject k = interp.get("a");
                List list = ((List)k.__tojava__(List.class));

                //System.out.println(k);
                System.out.println(list);


        }
}
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP