【问题标题】:How to obtain UTF-8 reader in PythonInterpreter (jython)?如何在 PythonInterpreter (jython) 中获取 UTF-8 阅读器?
【发布时间】:2015-02-03 16:03:03
【问题描述】:

我在我的 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'编码的阅读器?

根据python文档,编解码器模块中应该有'utf8'编码: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 上。

【问题讨论】:

  • 该文档仅将“utf_8”、“U8”、“UTF”和“utf8”显示为有效别名。没错,它还说“连字符而不是下划线也是有效的别名;因此,例如 'utf-8' 是 'utf_8' 编解码器的有效别名。”但“UTF_8”和“UTF-8”(即全大写版本)均未列出。您是否尝试过小写版本或实际列出的别名之一?
  • 我尝试了不同的选项('UTF-8'、'utf8'、'utf_8'),但结果是一样的。不过,我已经编辑了问题并将“UTF-8”替换为“utf8”,以使其更清晰。
  • 您的代码是否在交互式 Jython 会话中工作?哪个操作系统?哪个版本的 Java?此代码适用于我在 Java8u31 上运行在 Ubuntu 11.04 和 Windows 7 上的 Jython2.5.3。
  • 我在问题中添加了 OS、java 和 jboss 版本。我的代码是否在交互式 Jython 会话中工作?我不知道你到底是什么意思,所以可能不是......它被打包到 .war 并最终部署在 jboss 上。

标签: java python utf-8 jboss jython


【解决方案1】:

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

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 上下文时被调用。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-05-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多