我有一段 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")
最好的问候
最佳答案
确保你的项目类路径中有 jython-standalone.jar
而不是 jython.jar
因为 jython-standalone.jar
有 Python Lib 在 jar 中,这样您就不需要将它附加到 sys.path。
如果你使用的是 maven,你可以将它添加到 pom.xml
中:
<dependency>
<groupId>org.python</groupId>
<artifactId>jython-standalone</artifactId>
<version>2.7.0</version>
</dependency>
或者您可以下载 jar here .
对于你自己的 python 模块,把它放在 java 项目的类路径中,Jython 使用 java classplath 作为 __pyclasspath__
,这样你就可以避免硬编码。
关于Java与Jython,解决路径问题的优雅方式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11340743/