Jython :: which modules are available to PythonInterpreter and how to add more

本小妞迷上赌 提交于 2019-12-23 22:03:01

问题


I am using the Jython 2.5.3 PythonInterpreter class to evaluate some simple scripts but when I need to import any non-core modules I get an exception. Do I have to add some jython library jars in the CLASSPATH?

Narrow-down code that demonstrates the problem:

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

public class JythonTest {

    public static void main(String args[]) throws Exception {
        String scriptA = "import json"; // "import datetime" fails as well
        PythonInterpreter pi = new PythonInterpreter();
        PyCode code = pi.compile(scriptA);
        PyObject result = pi.eval(code);
    }
}

Running the above with only jython-2.5.3.jar in the CLASSPATH fails with the following trace:

 [java] ImportError: No module named json
 [java] 
 [java]     at org.python.core.Py.ImportError(Py.java:304)
 [java]     at org.python.core.imp.import_first(imp.java:755)
 [java]     at org.python.core.imp.import_module_level(imp.java:837)
 [java]     at org.python.core.imp.importName(imp.java:917)
 [java]     at org.python.core.ImportFunction.__call__(__builtin__.java:1220)
 [java]     at org.python.core.PyObject.__call__(PyObject.java:357)
 [java]     at org.python.core.__builtin__.__import__(__builtin__.java:1173)
 [java]     at org.python.core.imp.importOne(imp.java:936)
 [java]     at org.python.pycode._pyx0.f$0(<script>:2)
 [java]     at org.python.pycode._pyx0.call_function(<script>)
 [java]     at org.python.core.PyTableCode.call(PyTableCode.java:165)
 [java]     at org.python.core.PyCode.call(PyCode.java:18)
 [java]     at org.python.core.Py.runCode(Py.java:1275)
 [java]     at org.python.core.__builtin__.eval(__builtin__.java:484)
 [java]     at org.python.core.__builtin__.eval(__builtin__.java:488)
 [java]     at org.python.util.PythonInterpreter.eval(PythonInterpreter.java:198)
 [java]     at JythonTest.main(JythonTest.java:10)

回答1:


You seem to be using the Jython jar file that doesn't include the bundled Python files (the standard library in the /Lib folder). I believe it should work if you use the standalone jar instead. See

  • http://fwierzbicki.blogspot.se/2012/08/jython-253-final-released.html
  • http://wiki.python.org/jython/InstallationInstructions


来源:https://stackoverflow.com/questions/14641917/jython-which-modules-are-available-to-pythoninterpreter-and-how-to-add-more

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!