jython 简单入门
2021-10-25
·
hexWers

简单记录一下如何使用jython

jython是什么?

摘自百度百科 Jython是一种完整的语言,而不是一个Java翻译器或仅仅是一个Python编译器,它是一个Python语言在Java中的完全实现。

jython如何使用?

官方给出了几种方式,可以安装,可以用依赖导入,我选取maven依赖导入的方式

<dependency>
    <groupId>org.python</groupId>
    <artifactId>jython-slim</artifactId>
    <version>2.7.2</version>
</dependency>

文档地址:https://www.javadoc.io/doc/org.python/jython-standalone/2.7-rc2/index.html

简单使用

先把py给写出来,我放在E盘底下

test.py

print('abc hello!')

运行结果 在这里插入图片描述 然后我们写java

package python;

import org.python.core.PyInteger;
import org.python.core.PyObject;
import org.python.util.PythonInterpreter;

/**
 * @Description:
 * @Author: Cai
 * @CreateTime: 2021/11/25
 */

public class Test {
    public static void main(String[] args) {
        //创建python解释器对象,并执行test.py
        PythonInterpreter interp1 = new PythonInterpreter();
        interp1.execfile("E:\\test.py");
    }
}

执行结果: 在这里插入图片描述

package python;

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

import java.io.Reader;


/**
 * @Description:
 * @Author: Cai
 * @CreateTime: 2021/11/25
 */

public class Test {
    public static void main(String[] args) {
        //创建python解释器,运行python命令
        PythonInterpreter interpreter = new PythonInterpreter();
        interpreter.exec("import sys");
        interpreter.set("a", new PyString("hello"));
        interpreter.exec("print a");

        interpreter.cleanup();
        PyObject x = interpreter.get("x");
        System.out.println("x: " + x);

        interpreter.exec("x = 2+2");
        x = interpreter.get("x");
        System.out.println("x: " + x);

        System.out.println(interpreter.getLocals());
        System.out.println(interpreter.getSystemState());
    }
}



结果: 在这里插入图片描述

参考:https://blog.csdn.net/qq_42650988/article/details/96431078