47

Python 3 UnicodeEncodeError: 'ascii' codec can't encode...

 5 years ago
source link: http://www.phodal.com/blog/reslove-django-python3-unicode-encode-error-with-env-path/?amp%3Butm_medium=referral
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

之前在我的那个硬件网站【玩点什么】,遇到了一个 Python 的中文编码问题。大抵的问题是一个中文的 URL 的识别问题。

在访问 URL https://www.wandianshenme.com/play/category/搭建指南/ 的时候,报了一个错误:

UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-3: ordinal not in range

之前在网上搜索的相关结果都是 Python 2.7 下才有这个问题。然而,在相关的 python 代码里,我已经使用 # -*- coding: utf-8 -*- 声明了 UTF-8 编码,还是报了这个问题。

对于使用 Django,而且 Python 版本是 2.7 来说,可以尝试这么解决:

import sys
from importlib import reload

reload(sys)
if sys.version[0] == '2':
    reload(sys)
    sys.setdefaultencoding("utf-8")

我也尝试了这样的一个方法,但是不 work

export PYTHONIOENCODING=UTF-8

于是,之前便不了了之了。

直到最近我的 iTerm 自动将 Git 相关的内容变成了中文:

枚举对象: 5, 完成.
对象计数中: 100% (5/5), 完成.
使用 8 个线程进行压缩
压缩对象中: 100% (3/3), 完成.
写入对象中: 100% (3/3), 705 bytes | 705.00 KiB/s, 完成.
总共 3 (差异 2),复用 0 (差异 0)
remote: Resolving deltas: 100% (2/2), completed with 2 local objects.
To https://github.com/phodal/play
   5af94c0..573f947  master -> master

我又尝试去解决这个问题,结果发现是类似的问题,只需要:

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

这样一来,问题就解决了。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK