Jython安装及使用

  1. 安装 Jython
    1. Jython 2.7.0

安装 Jython

Jython 的官网为 http://www.jython.org

Jython 2.7.0

Download Jython 2.7.0 - Installer : Executable jar for installing Jython(可以使用 java -jar jython-installer-x.x.x.jar 进行安装)

参考:Jython 安装配置指南 for Windows,进行安装配置,注意可以添加C:\jython2.7.0\binpath环境变量,添加JYTHON_HOME变量,值为C:\jython2.7.0。在cmd中 输入jython验证安装成功。

Download Jython 2.7.0 - Standalone Jar : For embedding Jython in Java applications(在Java应用程序中嵌入Jython)

如果要在Java中使用Jython

import java.io.File;
import java.net.URISyntaxException;
import java.util.Properties;

import org.python.core.PyString;
import org.python.util.PythonInterpreter;

import com.jav.CompressedFileUtil;

public class Test1 {

    public static void main(String[] args) {
        Properties props = new Properties();
        props.put("python.home","/lib/jython.jar");
        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]);
        //加上上面这些可以解决 UnsupportedCharsetException问题,http://bugs.jython.org/issue2355,也可以在eclipse,run configurations 中在VM arguments 加上-Dpython.console.encoding=UTF-8

        PythonInterpreter interpreter = new PythonInterpreter();
//
//      interpreter.exec("days=('mod','Tue','Wed','Thu','Fri','Sat','Sun'); ");
//      interpreter.exec("print days[1];"); //可以直接执行Python语句

        String path = "";
        try {
            path = new File(new CompressedFileUtil().getClass().getClassLoader().getResource("").toURI()).getPath();
        } catch (URISyntaxException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        interpreter.exec("url = 'http://XXX.com/xxxx.html'");//可以直接执行Python语句
        interpreter.execfile(path + "\\agenttest.py");
        PyString  res = (PyString)interpreter.get("host"); //可以获得到Python中的变量值
        System.out.println(res);
    }
}

参考:java调用python方法总结



转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论,也可以邮件至 bin07280@qq.com

文章标题:Jython安装及使用

文章字数:417

本文作者:Bin

发布时间:2017-01-01, 22:53:15

最后更新:2019-08-06, 00:07:35

原始链接:http://coolview.github.io/2017/01/01/Java/Jython%E5%AE%89%E8%A3%85%E5%8F%8A%E4%BD%BF%E7%94%A8/

版权声明: "署名-非商用-相同方式共享 4.0" 转载请保留原文链接及作者。

目录