Python "myfirst.py" fails to "import mySecond.py". Both resources are in same package "test"
My main module was loaded with 'execFile', then i'm trying to import a .py module which is located in the same package as both my Runner java class as the main .py module.
But i'm not succeeding yet. My scenario;
My package structure:
/
/test/
/test/Runner.java
/test/myfirst.py
/test/mySecond.py
/test/__init__.py
In Runner.java:
InputStream mPython = getClass().getClassLoader().getResourceAsStream("test/myFirst.py" );
PythonInterpreter mInterp = new PythonInterpreter();
mInterp.execfile( mPython );
In myfirst.py
import sys
print sys.path
import mySecond
mySecond.hello()
In mySecond.py
def hello():
print "hi"
I've 开发者_JS百科tried all kind of things, offsets with test etc. without success.
Below the output when running 'debug' from my netbeans7 java project. Thought to show the sys.path as well. Maybe it helps getting a solution
debug:
['D:\\....\\ext\\Lib', '__classpath__', '__pyclasspath__/']
Exception in thread "main" Traceback (most recent call last):
File "<iostream>", line 3, in <module>
ImportError: No module named mySecond
Java Result: 1
BUILD SUCCESSFUL (total time: 4 seconds)
I assume it's to do with the .py files not being on disk, but to be loaded from my java classpath? Any ideas are welcome
UPDATE:
Looks had a more generic problem. An 'import os' even failed. My paths settings were wrong. Pointing to the lib directory seemed to fix it;
PySystemState mPyState = new PySystemState();
mPyState.path.insert(0,new PyString("C:\\jython2.5.1\\Lib"));
PythonInterpreter mInterp = new PythonInterpreter( null, mPyState );
I think this leads to the question;
How can i embed jython in my application without having to install jython251 on my harddrive (thus embedding the c:/jython251/lib directory)?
Found a good source on how importing works for Jython here
An answer for your update. You can use a standalone Jython.jar that contains the libs. You can get this jar by installing jython in standalone mode, or simply by copying the lib directory in the root of the standard Jython jar. A reference on that : Jython FAQ on distributing scripts
It sounds like Python's working directory is going to be the folder above test
, so you'll need to give the full module name (test.mySecond
), and you'll also need to make test
a Python module. To do that, just add a file at test/__init__.py
(it can be empty).
精彩评论