I have this Java code which I am using to run a python script using Jython ScriptEngine:
StringWriter writer = new StringWriter();
ScriptEngineManager manager = new ScriptEngineManager();
ScriptContext context = new SimpleScriptContext();
context.setWriter(writer);
ScriptEngine engine = manager.getEngineByName("python");
engine.eval(new FileReader("/Users/folder1/test.py"), context);
In my python script there are several module import statements and when I run the Java code I get error as javax.script.ScriptException: ImportError: No module named psycopg2. All the modules are installed in my machine and when I run the python script normally through CLI it executes. So my understanding is that Jython classpath is looking somewhere else for the python modules.
How can I check where does the Jython ScriptEngine looks for modules and then modify it include where actually my python modules are present? I am new to this so please forgive any lack of understanding.
Note: I have CentOS and python 2.7.5 installed on my machine
解决方案
sys.path is a list of strings that specifies where Jython (and Python) searches for modules. You can check its value like so:
engine.eval("import sys; print sys.path");
To add a directory to sys.path, use the JYTHONPATH environment variable. If yourmodule is installed in /path/to/modules/yourmodule, it would look like this:
export JYTHONPATH=/path/to/modules
Another way is to use the python.path property.
Unfortunately, in the case of psycopg2 the above won't help since that package is a C extension and therefore only compatible with CPython. Perhaps you can use the port of Psycopg for Ctypes instead.