java中使用Python的方法

使用PythonInterpreter执行python代码

pom.xml依赖

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

java中执行python片段

PythonInterpreter interpreter = new PythonInterpreter();
interpreter.exec("a='hello world'; ");
interpreter.exec("print a;");

原理解析

1//初始化Python编译器
PythonInterpreter interpreter = new PythonInterpreter();
protected PythonInterpreter(PyObject dict, PySystemState systemState, boolean useThreadLocalState) {
        this.cflags = new CompilerFlags();
        this.closed = false;
        this.globals = (PyObject)(dict != null ? dict : Py.newStringMap());
        this.systemState = systemState != null ? systemState : Py.getSystemState();//1.2
        this.setSystemState();
        this.useThreadLocalState = useThreadLocalState;
        PyModule module = new PyModule("__main__", this.globals);
        this.systemState.modules.__setitem__("__main__", module);
        if (Options.Qnew) {
            this.cflags.setFlag(CodeFlag.CO_FUTURE_DIVISION);
        }

        Py.importSiteIfSelected();
    }
1.1//PySystemState.initialize();
    public static synchronized void initialize...{
    preProperties = PrePy.getSystemProperties();
    postProperties = new Properties();
    ClassLoader context = Thread.currentThread().getContextClassLoader();
    ClassLoader sysStateLoader = PySystemState.class.getClassLoader();
    doInitialize(preProperties, postProperties, argv, classLoader, adapter);
}
1.2//doInitialize
    public static synchronized PySystemState doInitialize...{
     if (initialized) {
            return Py.defaultSystemState;
        } else {
            initialized = true;
            Py.setAdapter(adapter);
            boolean standalone = false;
            String jarFileName = Py.getJarFileName();
            if (jarFileName != null) {
                standalone = isStandalone(jarFileName);
            }

            initRegistry(preProperties, postProperties, standalone, jarFileName);
            initBuiltins(registry);
            defaultPath = initPath(registry, standalone, jarFileName);
            defaultArgv = initArgv(argv);
            defaultExecutable = initExecutable(registry);
            initPackages(registry);
            initConsole(registry);
            Py.defaultSystemState = new PySystemState();
            Py.setSystemState(Py.defaultSystemState);
            if (classLoader != null) {
                Py.defaultSystemState.setClassLoader(classLoader);
            }

            Py.initClassExceptions(getDefaultBuiltins());
            new PySyntaxError("", 1, 1, "", "");
            Py.defaultSystemState.__setattr__("_jy_console", Py.java2py(Py.getConsole()));
            return Py.defaultSystemState;
        }
}
2、//执行Python语法
  interpreter.exec("a='hello world'; ");
public void exec(String s) {
        this.setSystemState();
        Py.exec(Py.compile_flags(s, "<string>", CompileMode.exec, this.cflags), this.getLocals(), (PyObject)null);
        Py.flushLine();
}
2.1、//compile_flags
    mod node = ParserFacade.parse(data, kind, filename, cflags);
private static mod parse...{
    ...
        CharStream cs = new NoCloseReaderStream(reader);
    	BaseParser parser = new BaseParser(cs, filename, cflags.encoding);
   		return kind.dispatch(parser);
}
//mod,放入了解析后的Python信息
public abstract class mod extends PythonTree {
    public static final PyType TYPE;
    private static final PyString[] fields;
    private static final PyString[] attributes;
    ...
}
2.2、//编译
public static PyCode compile_flags(mod node, String name, String filename, boolean linenumbers, boolean printResults, CompilerFlags cflags) {
        return CompilerFacade.compile(node, name, filename, linenumbers, printResults, cflags);
    }

PythonCompiler compiler = new LegacyCompiler();
public class LegacyCompiler implements PythonCompiler {
    ...
    public static PyCode compile(mod node, String name, String filename, boolean linenumbers, boolean printResults, CompilerFlags cflags) {
        try {
            PythonCodeBundle bundle = compiler.compile(node, name, filename, linenumbers, printResults, cflags);
            return bundle.loadCode();
        } catch (Throwable var7) {
            throw ParserFacade.fixParseError((ExpectedEncodingBufferedReader)null, var7, filename);
        }
    }
    public PyCode loadCode() throws Exception {
            return BytecodeLoader.makeCode(this.name, this.ostream().toByteArray(), this.filename);
    }
    ...
}

public static PyCode makeCode(String name, byte[] data, String filename) {
    try {
        Class<?> c = makeClass(name, data);
        Constructor<?> cons = c.getConstructor(String.class);
        Object instance = cons.newInstance(filename);
        PyCode result = ((PyRunnable)instance).getMain();
        return result;
    } catch (Exception var7) {
        throw Py.JavaError(var7);
    }
}

java中执行Python文件

PythonInterpreter interpreter = new PythonInterpreter();
interpreter.execfile("src\\test\\java\\com\\jsq\\sayHello.py");

原理解析

//和片段差不多,只是从文件中读取出

java中执行Python文件中的方法(有参数输入)

PythonInterpreter interpreter = new PythonInterpreter();
interpreter.execfile("src\\test\\java\\com\\jsq\\sayHello2.py");
PyFunction pyFunction = interpreter.get("func", PyFunction.class);
String b = "python";
PyObject pyObject = pyFunction.__call__(new PyString(b));
System.out.println(pyObject);

java中执行Python文件中的方法(无参数输入)

PythonInterpreter interpreter = new PythonInterpreter();
interpreter.execfile("src\\test\\java\\com\\jsq\\sayHello3.py");
PyFunction pyFunction = interpreter.get("func", PyFunction.class);
PyObject pyObject = pyFunction.__call__();
System.out.println(pyObject);
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值