2012-07-05 41 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__,所以你避免了硬編碼。