import locale
prefered_encoding = locale.getpreferredencoding()
prefered_encoding 'ANSI_X3.4-1968'
我正在使用名为inginious的框架,并使用web.py来呈现其模板。
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 chars,小例子
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title feedback-modal-title">
חישוב האיברים הראשונים בסדרה של איבר ראשון חיובי ויחס שלילי:
<span class="red-text">אי הצלחה</span>
我这样打开它:
open('/path/to/feedback.html').read()
和编码失败的行是希伯来字符所在的位置。
我尝试在~/.bashrc
中设置一些环境变量:
export PYTHONIOENCODING=utf8
export LC_ALL=en_US.UTF-8
export LANG=en_US.UTF-8
export LANGUAGE=en_US.UTF-8
用户centos
下的
巧妙的框架在python3.5站点包下安装为pip
。它由用户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'
我使用setenv方法编辑了/etc/httpd/conf/httpd.conf
:
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 :(得分:1)
在阅读文件时终于找到了答案 改变了
open('/path/to/feedback.html').read()
到
import codecs
with codecs.open(file_path,'r',encoding='utf8') as f:
text = f.read()
如果有人有更通用的方法可行,我会接受他的回答
答案 1 :(得分:1)
Python 2 + 3解决方案将是:
import io
with io.open(file_path, mode='r', encoding='utf8') as f:
text = f.read()
请参阅io.open
的文档。