python3默认编码使用

问题描述:

import locale 
prefered_encoding = locale.getpreferredencoding() 
prefered_encoding 'ANSI_X3.4-1968' 

我使用了一个名为inginious框架,它使用web.py来呈现它的模板的Apache WSGI的UnicodeDecodeError ASCII。python3默认编码使用

web.template.render(os.path.join(root_path, dir_path), 
            globals=self._template_globals, 
            base=layout_path) 

渲染作品在我的本地不是我的临时服务器上。

他们都运行python3。我看到web.py强制utf-8

在Python2编码只(这是从我手中)

def __str__(self): 
    self._prepare_body() 
    if PY2: 
     return self["__body__"].encode('utf-8') 
    else: 
     return self["__body__"] 

这里是堆栈跟踪

t = self._template(name), 
File "/lib/python3.5/site-packages/web/template.py", line 1028, in _template, 
self._cache[name] = self._load_template(name), 
File "/lib/python3.5/site-packages/web/template.py", line 1016, in _load_template 
return Template(open(path).read(), filename=path, **self._keywords) 
File "/lib64/python3.5/encodings/ascii.py", line 26, in decode 
return codecs.ascii_decode(input, self.errors)[0] 
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe2 in position 83: ordinal not in range(128), 

我的HTML不包括hebew字符,小例子

<div class="modal-content"> 
        <div class="modal-header"> 
         <button type="button" class="close" data-dismiss="modal">&times;</button> 
         <h4 class="modal-title feedback-modal-title"> 
          חישוב האיברים הראשונים בסדרה של איבר ראשון חיובי ויחס שלילי: 
          <span class="red-text">אי הצלחה</span> 

我打开它像这样:

open('/path/to/feedback.html').read() 

并且编码失败的行是希伯来字符的位置。

我试着在~/.bashrc设置一些环境变量:巧妙的框架下python3.5站点包安装为pip用户centos

export PYTHONIOENCODING=utf8 
export LC_ALL=en_US.UTF-8 
export LANG=en_US.UTF-8 
export LANGUAGE=en_US.UTF-8 

。它的用户下送达的Apache服务器apache

试图在代码中设置环境变量(应用程序的初始化过程中),这样在Apache WSGI会意识到他们的

import os 
os.environ['LC_ALL'] = 'en_US.UTF-8' 
os.environ['LANG'] = 'en_US.UTF-8' 
os.environ['LANGUAGE'] = 'en_US.UTF-8' 

我有编辑/etc/httpd/conf/httpd.conf使用setenv方法:

SetEnv LC_ALL en_US.UTF-8 
SetEnv LANG en_US.UTF-8 
SetEnv LANGUAGE en_US.UTF-8 
SetEnv PYTHONIOENCODING utf8 

,并使用sudo service httpd restart,仍然没有运气重新启动。

我的问题是,解决这个问题的最佳做法是什么?我明白这有些瑕疵,但我想了解下划线原因以及如何解决这个问题。

谢谢!

+0

'ANSI_X3.4-1968' =='ASCII'。 –

+0

您需要向我们展示回溯是什么以及如何重现它。 –

+0

我已经添加了堆栈跟踪和一些更多的代码,但为了重现,你将不得不安装inginious框架,这不是一个有效的建议,所以我最好的选择是描述问题很好 – WebQube

终于找到了答案阅读从

open('/path/to/feedback.html').read() 

更改的文件 时

import codecs 
with codecs.open(file_path,'r',encoding='utf8') as f: 
    text = f.read() 

如果任何人有一个,将工作更普遍的做法,我会接受他的答案

Python 2 + 3解决方案应该是:

import io 

with io.open(file_path, mode='r', encoding='utf8') as f: 
    text = f.read() 

请参阅io.open的文档。