1.問題:提示不能夠導入site module
一般在Java中調用Python,執行代碼流程如下:
Properties props = new Properties();
props.put("python.home", "F:\\spring-app\\src\\main\\webapp\\WEB-INF\\lib");
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[]);
PythonInterpreter interpreter = new PythonInterpreter();
interpreter.execfile("F:\\spring-app\\src\\main\\webapp\\WEB-INF\\lib\\main.py");
PyFunction func = (PyFunction) interpreter.get("function_name", PyFunction.class );
PyObject pyobj = func.__call__();
隻要在代碼中添加:props.put(“python.import.site”, “false”);即可處理上面的錯誤。
2.本人還遇到一種情況,添加props.put(“python.import.site”, “false”);之後仍然報錯
這種情況代碼如下:
PySystemState sys = Py.getSystemState();
sys.path.add("F:\\spring-app\\src\\main\\webapp\\WEB-INF\\lib");
Properties props = new Properties();
props.put("python.home", "F:\\spring-app\\src\\main\\webapp\\WEB-INF\\lib");
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[]);
PythonInterpreter interpreter = new PythonInterpreter();
interpreter.execfile("F:\\spring-app\\src\\main\\webapp\\WEB-INF\\lib\\main.py");
PyFunction func = (PyFunction) interpreter.get("function_name", PyFunction.class );
PyObject pyobj = func.__call__();
可以看出隻是多了兩行代碼:
PySystemState sys = Py.getSystemState();
sys.path.add("F:\\spring-app\\src\\main\\webapp\\WEB-INF\\lib");
代碼主要是将上面路徑加入path中,這樣可以在Python代碼中import 自己的Python 檔案。加上上面代碼錯誤再次出現,但如果将上面兩行代碼放在,props.put(“python.import.site”, “false”); 之後,錯誤消除。
測試發現隻要執行Py.getSystemState(); 再執行props.put(“python.import.site”, “false”); 便不起作用,其中問題還望各位大牛指點一二!