简体   繁体   中英

PythonInterpreter importing java classes

I have the following file structure:

src
|___mod
|   |__ __init__.py
|   |__ pycode.py
|   |__ javacode.java
|
|___main
    |__ start.java

contents of pycode.py:

from mod import javacode as jv
...

Inside start.java , I try to run pycode.py with the python interpreter.

PythonInterpreter py = new PythonInterpreter();
py.exec("from mod.pycode import *");

However, I get the following error:

ImportError: cannot import name javacode

It's confusing because it seems to be able to find the package, but for some reason fails to find the file. I have infact verified that it found the package because it complains if you supply the wrong package name.

To give more information, I am running the program on windows in eclipse. I am using the pydev plugin for eclipse. I have added the bin folder of the project as a source folder for pydev (as suggested by one source), and I have the following at the start of my program:

static {
    PythonInterpreter.initialize(System.getProperties(), PySystemState.getBaseProperties(),
            null);
}

Can anyone give me an idea on how I can fix this?

The reason why it was not working is because I placed javacode.java in a python package.

According to the book Jython Essentials , doing this will mark the java file as a python module:

Jython also allows access to Java classes and packages through the import statements. Jython is able to load classes through the underlying Java Virtual Machine (JVM), both from the Java classpath and from the directories in sys.path. Conceptually, you can think that for the purpose of loading Java classes, the directories in sys.path have been appended to the classpath. This means there is no need to mark Java packages on sys.path with __init__.py modules, because that would make them Python packages.

So after this, I organized the files as such:

src
|___pymodules
|   |__ __init__.py
|   |__ pycode.py
|
|___mod
|   |__ javacode.java
|
|___main
    |__ start.java

Inside start.java :

PythonInterpreter py = new PythonInterpreter();
py.exec("from pymodules.pycode import *");

The program now executes perfectly both in eclipse and even after making it into a standalone jar

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM