How to check the classpath where Jython ScriptEngine looks for python module?

人盡茶涼 提交于 2019-12-02 14:05:18

问题


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


回答1:


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.




回答2:


An alternative way to add path to folder with custom python libs using ScriptEngine:

engine.eval("import sys; sys.path.append(\"/some/path/to/folder/withpylibs\")");


来源:https://stackoverflow.com/questions/33309860/how-to-check-the-classpath-where-jython-scriptengine-looks-for-python-module

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!