我有一段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")
問候
你不需要硬編碼'C:/ jython2.5.2/Lib';正確安裝的'jython.jar'應該知道它的位置。 – 2012-07-05 09:35:22
好吧,我已經明白了,因爲它沒有工作,請問,我可能錯過了哪些步驟,以便它沒有「正確安裝」? thx – user1340802 2012-07-05 12:01:35
我剛剛運行安裝程序腳本,它沒有任何問題。你是否可能移動安裝? – 2012-07-05 12:10:44