如何在PythonInterpreter(jython)中获取UTF-8阅读器?

时间:2015-02-03 16:03:04

标签: java python utf-8 jboss jython

我在我的Web应用程序中使用嵌入式Jython(版本2.5.3),我尝试在我的Java代码中执行此操作:

PythonInterpreter pythonInterpreter = new PythonInterpreter();
pythonInterpreter.exec("import codecs");
pythonInterpreter.exec("codecs.getreader('utf8')");

但是我收到了这个错误:

File "<string>", line 1, in <module>
File "__pyclasspath__/codecs$py.class", line 920, in getreader
LookupError: no codec search functions registered: can't find encoding 'utf8'

读者怎么能用'utf8&#39;编码得到正确的?

根据python文档,应该有&#39; utf8&#39;编解码器模块中可用的编码:https://docs.python.org/2/library/codecs.html#standard-encodings(允许使用大写/小写和连字符/下划线)。

我使用的是Windows 7,java 1.7.0_71。操作系统无关紧要我想 - 这是在jboss(版本7.2)上运行的Web应用程序。 jython-standalone-2.5.3.jar和常规jython-2.5.3.jar都会出现问题。

1 个答案:

答案 0 :(得分:2)

我设法找到了解决此问题的方法 - 这是一个配置错误。在将代码更改为:

之后,它现在可以工作了
import java.util.Properties;
import org.python.util.PythonInterpreter;

(...)

Properties properties = new Properties();
properties.setProperty("python.path", pythonPath);
PythonInterpreter.initialize(System.getProperties(), properties, new String[] { "" });
PythonInterpreter pythonInterpreter = new PythonInterpreter();
pythonInterpreter.exec("import codecs");
pythonInterpreter.exec("codecs.getreader('utf8')");

其中pythonPath是部署的WAR中jython-2.5.3.jar中“Lib”目录的路径。

我最终将它全部包装在一些PostConstruct Spring方法中,该方法在启动Spring上下文时被调用。