【发布时间】:2012-07-05 15:29:57
【问题描述】:
我有一段 Java 代码,使用 Jython 调用一些 Python 库,这个库依赖于外部 Jython 经典库,如 re 用于正则表达式等,所以我有这种代码:
PythonInterpreter interpreter = new PythonInterpreter(null, new PySystemState());
PySystemState sys = Py.getSystemState();
// below: so that my own library find necessary 'batteries included' Python libs
sys.path.append(new PyString("C:/jython2.5.2/Lib")); // (path1)
// below: i put my own Python library inside the Java package for clarity
// and be able to package everything in jar, well, maybe is it no a good idea?
// also i am wondering, because myfile.py remain inside /src subdirectories
// while after compiling Eclipse will put most in /bin subidrectories but not the *.py files
// thus doing some:
// MyJythonFactory..class.getProtectionDomain().getCodeSource().getLocation().toString()
// will not help to rebuild the ..myJavaProject/src/my/domain/mypackage
sys.path.append(new PyString("D:/eclipseWorkspace/myJavaProject/src/my/domain/mypackage")); (path2)
interpreter.exec("from mylib import myfunc"); //(A)
PyObject myPyFunction = interpreter.get("myfunc");
顺便说一句,我不喜欢我需要更改和硬编码路径 (path1) 和 (path2) 的事实
您是否发现了一种避免这种情况并添加一些“whereami”自动检测路径功能的优雅方法(至少对于(path2))?
看起来我需要 (path1) 和 (path2) => 以便 (A) 工作!
我还可以将我的问题重新表述为没有任何 ImportError: No module named myModule 或如何避免硬编码类似以下内容的优雅方式:
PySystemState sys = Py.getSystemState();
sys.path.append("where/my/python/libs/live/while/they/are/at/the/same/place/as/my/current/java/class")
最好的问候
【问题讨论】:
-
你不需要硬编码
C:/jython2.5.2/Lib;正确安装的jython.jar应该知道它的位置。 -
好吧,我已经知道了,因为如果没有它就无法工作,请问有哪些步骤是我可能错过的,所以它没有“正确安装”?谢谢
-
我刚刚运行了安装程序脚本,它运行起来没有任何问题。您是否移动了安装?
-
实际上它可以工作,但是在
mypythonmodules.py内部,我有例如import re模块和其他模块,看起来我需要为Jython.jar 提供这些库的路径,这就是为什么我以添加此路径结束。见:stackoverflow.com/questions/471000/jython-and-python-modules
标签: java import jython sys.path