在eclipse中用java調用python報錯 Exception in thread "main" ImportError: Cannot import site module and its dependencies


 

最近做項目需要用java調用python,配置了jython后,運行了例子代碼:

獲得一個元組里面的元素:

import org.python.util.PythonInterpreter;
public class FirstJavaScript {
    public static void main(String args[]) {

        PythonInterpreter interpreter = new PythonInterpreter();
        interpreter.exec("days=('mod','Tue','Wed','Thu','Fri','Sat','Sun'); ");
        interpreter.exec("print days[1];");

    }// main
}

 

運行時報錯:

Exception in thread "main" ImportError: Cannot import site module and its dependencies: No module named site
Determine if the following attributes are correct:
* sys.path: ['C:\\(你的項目地址)', '__classpath__', '__pyclasspath__/']
This attribute might be including the wrong directories, such as from CPython
* sys.prefix: C:(你的項目地址)
This attribute is set by the system property python.home, although it can
be often automatically determined by the location of the Jython jar file

You can use the -S option or python.import.site=false to not import the site module

 

 我們只需要把代碼改為以下這個例子就可以順利執行了。

 

Properties props = new Properties();
     props.put("python.home", "path to the Lib folder");
     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("days=('mod','Tue','Wed','Thu','Fri','Sat','Sun'); ");
     interpreter.exec("print days[1];");

 

 執行結果是Tue

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM