Jython 报错: This attribute might be including the wrong directories, such as from CPython * sys.prefi

it2022-05-05  70

今天在使用 Jython 调用 Python 脚本的时候出现了异常:

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: ['/Users/dongguabai/develope/maven/repository/org/python/jython/2.7.0/Lib', '__classpath__', '__pyclasspath__/'] This attribute might be including the wrong directories, such as from CPython * sys.prefix: /Users/dongguabai/develope/maven/repository/org/python/jython/2.7.0 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

使用的是 Jython,依赖:

<dependency> <groupId>org.python</groupId> <artifactId>jython</artifactId> <version>2.7.0</version> </dependency>

调用方法:

public class Test { public static void main(String[] args) throws IOException { String path = ResourceUtils.getFile(ResourceUtils.CLASSPATH_URL_PREFIX + "py/test.py").getPath(); PythonInterpreter interpreter = new PythonInterpreter(); interpreter.execfile(path); PyFunction function = interpreter.get("my_test",PyFunction.class); PyObject pyobject = function.__call__(new PyString("huzhiwei"),new PyString("25")); System.out.println("anwser = " + pyobject.toString()); } }

解决方案:

调用方法修改增加上面几行:

public class Test { public static void main(String[] args) throws IOException { 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]); String path = ResourceUtils.getFile(ResourceUtils.CLASSPATH_URL_PREFIX + "py/test.py").getPath(); PythonInterpreter interpreter = new PythonInterpreter(); interpreter.execfile(path); PyFunction function = interpreter.get("my_test",PyFunction.class); PyObject pyobject = function.__call__(new PyString("huzhiwei"),new PyString("25")); System.out.println("anwser = " + pyobject.toString()); } }

或者将依赖修改为:

<dependency> <groupId>org.python</groupId> <artifactId>jython-standalone</artifactId> <version>2.7.1</version> </dependency>

References:

https://www.jianshu.com/p/cefdaccd3fd3

https://blog.csdn.net/hzw19920329/article/details/77509497

https://bugs.jython.org/issue2355


最新回复(0)