2012-07-05 100 views
3

我有一段Java代码,使用Jython调用一些Python库,这个库依赖于外部的Jython经典libraryies像re对正则表达式和其他人,所以我有这样的代码:用Jython实现Java,解决路径问题的优雅方法?

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"); 

BTW,我不喜欢的事实,我需要改变和硬编码路径都和(path1)(path2)

你看到一个优雅的方式来避免这一点,增加一些“WHEREAMI”自动检测路径功能(至少(path2))?

看起来像我需要两个(路径1)和(路径2)=>以便(A)的作品!

我也可以重新我的问题是什么优雅的方式,你会发现到没有任何导入错误:没有模块名为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") 

问候

+0

你不需要硬编码'C:/ jython2.5.2/Lib';正确安装的'jython.jar'应该知道它的位置。 – 2012-07-05 09:35:22

+0

好吧,我已经明白了,因为它没有工作,请问,我可能错过了哪些步骤,以便它没有“正确安装”? thx – user1340802 2012-07-05 12:01:35

+0

我刚刚运行安装程序脚本,它没有任何问题。你是否可能移动安装? – 2012-07-05 12:10:44

回答

1

确保你的项目类路径中有jython-standalone.jar而不是jython.jar,因为jython-standalone.jar在jar里面有Python Lib,所以你不需要把它附加到sys.path中。

如果你正在使用maven,你可以添加这pom.xml

<dependency> 
    <groupId>org.python</groupId> 
    <artifactId>jython-standalone</artifactId> 
    <version>2.7.0</version> 
</dependency> 

,或者你可以下载JAR here

为你自​​己的python模块把它放在java项目classpath中,Jython使用java classplath作为__pyclasspath__,所以你避免了硬编码。