[英]Jython standalone jar not able to find site_packages
我正在與 Jython 集成以運行 python 腳本(它自己運行良好)。 我將 Jython Standalone 2.7.1 添加到我的 pom.xml,但是它似乎無法識別在site_packages
下安裝的包。 我已經嘗試過像這里和這里提到的建議。 然而,它們似乎都不起作用。 如果我從獨立的 jar 移動到非獨立的 jar,我會得到ImportError: No module named os
。 使用獨立 jar,我可以更進一步,但出現如下錯誤。 test_framework
是site_packages
安裝的包site_packages
ImportError: No module named test_framework
這是代碼。 似乎未設置某些路徑,但我無法弄清楚是哪一個。
Properties props = new Properties();
props.put("python.home", "x/.m2/repo/org/python/jython-standalone/2.7.1");
props.put("jython.home", "x/.m2/repo/org/python/jython-standalone/2.7.1");
props.put("python.console.encoding", "UTF-8");
props.put("python.security.respectJavaAccessibility", "false");
props.put("python.import.site", "false");
Properties preprops = System.getProperties();
PythonInterpreter.initialize(preprops, props, new String[0]);
PythonInterpreter interpreter = new PythonInterpreter();
interpreter.exec("import sys\n" +
"sys.path.append('src/test/resources/pythonScript')" +
"\nimport pythonScript.test_command as sc");
PyObject someObj = interpreter.eval("sc.TestCommand()");
PyObject someFunc = someObj.__getattr__("deliver_command");
似乎未設置某些路徑,但我無法弄清楚是哪一個。
當您使用 Jython 獨立 jar 時, python.home
應該指向您的 Lib 文件夾。 提取 Jython 獨立 jar,將“Lib”文件夾復制到某個位置並將python.home
指向該路徑。
props.put("python.home", "/path/to/folder/Lib");
為了安裝軟件包,請將其復制到 Lib 文件夾的根目錄。 示例以使用包“test_framework”將其粘貼到 Lib 文件夾並使用import test_framework
導入包。
此外,當您使用獨立 jar 時,您不需要設置jython.home
屬性
我遇到了同樣的問題。 我通過將以下內容添加到我的腳本中來修復它:
from os.path import split, join
import site
for prefix in set(site.PREFIXES):
path, subdir = split(prefix)
if subdir == 'bin':
lib = join(path, 'lib', 'python2.7', 'site-packages')
site.addsitedir(lib)
我的 site.PREFIXES 只有兩個重復的條目,所以我使用 set() 去刪除點亮的。 我沒有使用的一個想法是在將其添加為站點目錄之前確保該路徑存在。 另外,我對 Python 的版本進行了硬編碼; 總有一天 Jython 將升級到 3.x,這將需要重新訪問。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.