Import module error: calling python script with jython in java program
I am trying to execute a python file from netbeans using jython
in a java program. My code looks like this:
PythonInterpreter.initialize(System.getProperties(), System.getProperties(),
new String[0]);
PythonInterpreter interp = new PythonInterpreter();
interp.execfile("as1.py");
mistake:
Traceback (most recent call last):
File "as1.py", line 2, in <module>
import datetime
ImportError: No module named datetime
and also the interdependent python files, also not importing them, are in the same directory.
as:
PythonInterpreter.initialize(System.getProperties(), System.getProperties(), new String[0]);
PythonInterpreter interp = new PythonInterpreter();
interp.execfile("calen.py");
Python files:
calen.py:
from as1 import *
print ( "I am printing" + str(Moh(1000).run()))
as1.py
from time import time
import datetime
class Moh:
def __init__(self, n):
self.n = n
def run(self):
data = [1,2,3,4,5]
start = time()
for i in range(self.n):
data.append(i)
end = time()
return ( end - start )/self.n
if __name__ == "__main__":
print ( "I am printing" + str(Moh(1000).run()))
mistake:
Traceback (most recent call last):
File "calen.py", line 1, in <module>
from as1 import *
ImportError: No module named as1
+3
source to share
1 answer
It is very important to set "python.path" for PythonInterpreter so that it can load your as1 module. To do this, you must initialize PythonInterpreter like this:
Properties properties = System.getProperties();
properties.put("python.path", PATH_TO_PARENT_DIRECTORY_OF_AS1_PY);
PythonInterpreter.initialize(System.getProperties(), properties, new String[0]);
PythonInterpreter interp = new PythonInterpreter();
interp.execfile("calen.py");
+2
source to share