看来我错过了什么。
当使用 Jython 在 Java 中运行我的 Python 代码时,会生成 Java 字节码文件(test.py -> test@py.class)。
我可以直接使用 java 运行这些类吗?
换句话说,我想做这个:
$ java test@py [additional cp args]
工作。
意图:编写 Python 代码而不必放弃源代码。
最佳答案
这是对我有用的:
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:
$JYTHON_HOME/jython $JYTHON_HOME/Lib/compileall.py .
将 test_p.py 移开,以证明它未被使用:
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 - 使用 java 运行 jython 字节码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2583192/