简体   繁体   中英

How to obtain UTF-8 reader in PythonInterpreter (jython)?

I am using embedded Jython (version 2.5.3) in my web application and I try to do this in my Java code:

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

But I get this error:

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'

How can the reader with 'utf8' encoding be obtained properly?

According to the python documentation, there should be 'utf8' encoding available in codecs module: https://docs.python.org/2/library/codecs.html#standard-encodings (lower / upper case and hyphen / underscore are all allowed).

I use Windows 7, java 1.7.0_71. OS should not matter I guess - this is the web application run on jboss (version 7.2). The problem occurs on both jython-standalone-2.5.3.jar and regular jython-2.5.3.jar.

I managed to find a solution to this problem - this was a configuration error. It works now, after changing the code to:

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')");

where pythonPath is the path to the “Lib” directory in the jython-2.5.3.jar, in the deployed WAR.

I ended up wrapping it all up in some PostConstruct Spring method, which is invoked when starting Spring context.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM