Load Python class through Jython

635 views Asked by At

I'm trying to load a Python class by embedding Jython in my Java application.

The code I have so far is

        String pythonRoot = Main.class.getResource("/python").getPath();

        PySystemState state = new PySystemState();
        PyObject importer = state.getBuiltins().__getitem__(Py.newString("__import__"));

        PyObject sysModule = importer.__call__(Py.newString("sys"));

        final PyString pythonPath = Py.newString(pythonRoot);
        PyList path = (PyList) sysModule.__getattr__("path");
        path.add(pythonPath);

        PyModule module = (PyModule) importer.__call__(Py.newString("building.blah.again.blah2.Test"));
        PyObject klass = module.__getattr__(Py.newString("Address"));
        AddressInterface ai = (AddressInterface) klass.__call__().__tojava__(AddressInterface.class);

The class I'm trying to access can be found in

/python/building/blah/again/blah2/Test.py

And the name of the class is

Address

However, this gives me the exception

Exception in thread "main" ImportError: No module named blah2

If I place some file in the directory above, like so

/python/building/blah/again/Test.py

This gives me the exception

Exception in thread "main" ImportError: No module named again

It's as if he is actively refusing to recognize directories that contains files. What can be the problem here and how might I proceed to get around this?

1

There are 1 answers

0
stewori On BEST ANSWER

If you added the path of your module to the Python-path, which you did via path.add(pythonPath);, the import-command expects only the name of the module, not the full path, i.e. PyModule module = (PyModule) importer.__call__(Py.newString("Test")); Further, you should confirm that actually the right path was added by printing the contents of the path-list. Also note that your class-declaration in Test.py must extend the Address-java-interface for toJava to work (I just mention this because this is also a common source of error).

That said, your way of using Jython appears somewhat cumbersome to me. If I were you, I would do this stuff (adding the path, doing the import) in a python-script, run it via org.python.util.PythonInterpreter (http://www.jython.org/javadoc/org/python/util/PythonInterpreter.html) and retrieve the class-PyObject via the eval or get-method.