使用java运行jython字节码 [英] running jython bytecode using java

查看:283
本文介绍了使用java运行jython字节码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

看起来我错过了什么。

当使用Jython在Java中运行我的Python代码时,会生成Java字节码文件(test.py - > test @ py.class)。

When using Jython to run my Python code in Java, Java bytecode files are generated (test.py -> test@py.class).

我可以直接使用java运行这些类吗?

Can I run these classes directly using java?

换句话说,我想要这样做:

In other words, I want to make this:

$ java test@py [additional cp args]

工作。

意图:编写Python代码而不必放弃源代码。

The intent: writing Python code and not having to give away source code.

推荐答案

这对我有用:

test_p .py:

def foo():
  print 'test from Python'

TestJ.java:

import org.python.core.PyFrame;
import org.python.core.PyFunctionTable;
import org.python.util.PythonInterpreter;

public class TestJ
{
  public static void main(String[] args)
  {
    final PythonInterpreter interpreter = new PythonInterpreter();

    interpreter.exec("import sys");

    try
      {
        final Class<?> clazz = Class.forName("test_p$py");

        final java.lang.reflect.Constructor constructor
          = clazz.getConstructor(String.class);

        final PyFunctionTable module = (PyFunctionTable)constructor.newInstance("");

        final java.lang.reflect.Method method
          = clazz.getDeclaredMethod("foo$1",
                                    PyFrame.class,
                                    org.python.core.ThreadState.class);

        method.invoke(module,
                      (PyFrame)interpreter.eval("sys._getframe()").__tojava__(PyFrame.class),
                      org.python.core.Py.getThreadState());
      }
    catch (final ClassNotFoundException e)
      { e.printStackTrace(); }
    catch (final NoSuchMethodException e)
      { e.printStackTrace(); }
    catch (final InstantiationException e)
      { e.printStackTrace(); }
    catch (final IllegalAccessException e)
      { e.printStackTrace(); }
    catch (final java.lang.reflect.InvocationTargetException e)
      { e.printStackTrace(); }
  }
}

将test_p.py编译成test_p $ py.class :

Compile test_p.py into test_p$py.class:

$JYTHON_HOME/jython $JYTHON_HOME/Lib/compileall.py .

将test_p.py移开,以证明它没有被使用:

Move test_p.py out of the way, to prove it's not being used:

mkdir hidden
mv test_p.py hidden/

编译:

javac -cp $JYTHON_HOME/jython.jar TestJ.java

测试:

java -cp $JYTHON_HOME/jython.jar:. TestJ

输出:

test from Python

这篇关于使用java运行jython字节码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆