V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
chengxiao
V2EX  ›  Python

关于'ascii' codec can't encode characters in position 的问题

  •  
  •   chengxiao · 2018-01-12 11:36:54 +08:00 · 4449 次点击
    这是一个创建于 2286 天前的主题,其中的信息可能已经有所发展或是发生改变。
    为什么已经用了 Python3 了 而且在头部加了# encoding=utf8
    还是会出现 ascii' codec can't encode characters in position 的报错

    快被这个问题搞疯了 ,Mac 本机测试正常,以 uwsgi 跑在 ubuntu 上就报错
    9 条回复    2018-01-12 14:31:28 +08:00
    lhx2008
        1
    lhx2008  
       2018-01-12 11:39:45 +08:00 via Android
    命令行可能不支持 unicode 输出,print 前先 encode
    chengxiao
        2
    chengxiao  
    OP
       2018-01-12 11:41:52 +08:00
    @lhx2008 是 Django 里用的 ImageFiled, 只要上传中文名称的图片 就报错
    xawsolevo
        3
    xawsolevo  
       2018-01-12 12:33:49 +08:00
    可以试试先 encode 到 latin 再 decode 为 utf8
    est
        4
    est  
       2018-01-12 12:34:50 +08:00
    用的 windows ?
    chengxiao
        5
    chengxiao  
    OP
       2018-01-12 13:22:05 +08:00
    @est 不啊 Ubuntu16.04 Nginx uwsgi python3.6
    privatez
        6
    privatez  
       2018-01-12 13:24:49 +08:00
    import sys

    reload(sys)

    sys.setdefaultencoding('utf8')

    试试看 QAQ
    Arnie97
        7
    Arnie97  
       2018-01-12 13:59:32 +08:00 via Android   ❤️ 1
    1. 请将$LANG 或$LC_ALL 设置为 en_US.utf8 或 zh_CN.utf8。
    2. 如果不存在上述的 locale,先用 locale-gen 生成。具体操作可以参考 https://help.ubuntu.com/community/Locale
    3. 如果不考虑 Python 2 的兼容性,不必加 encoding 头部。Python 3 会忽略这行注释,强制要求 UTF-8 源码。

    @est 楼主发帖时已经说了 Ubuntu ;并且 Windows 无法将代码页设置为 ASCII。

    @xawsolevo 就是因为你这种人才会发生 /t/421212 这种情况😂
    chengxiao
        8
    chengxiao  
    OP
       2018-01-12 14:14:52 +08:00
    @Arnie97 多谢 我去尝试下 现在也是觉得问题出在系统环境这里
    chengxiao
        9
    chengxiao  
    OP
       2018-01-12 14:31:28 +08:00
    @Arnie97 非常感谢 问题解决了
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   965 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 29ms · UTC 21:52 · PVG 05:52 · LAX 14:52 · JFK 17:52
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.