我有一段 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")
此致