我有一段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)
您是否看到一种优雅的方法来避免这种情况并添加一些“wheremi”自动检测路径功能(至少对于
(path2)
)?看起来我需要(路径1)和(路径2)=>这样(a)才行!
我还可以将我的问题重新表述为,您会发现什么样的优雅方式没有任何重要的错误:没有名为my module的模块,或者如何避免硬编码,例如:
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
在jar中有python库,所以不需要将其附加到sys.path。
如果您使用的是maven,可以将其添加到pom.xml
:
<dependency>
<groupId>org.python</groupId>
<artifactId>jython-standalone</artifactId>
<version>2.7.0</version>
</dependency>
或者你可以下载jarhere。
对于您自己的python模块,将其放在java项目类路径中,jython使用java classplath作为
__pyclasspath__
,因此避免硬编码。关于java - Java与Jython合作,以优雅的方式解决路径问题?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11340743/