python print中文出现UnicodeEncodeError: 'ascii' codec can't encode characters
不支持中文,怎么解决?
网友回复
解决办法
(1)设置环境变量LANG 在linux或Mac上设置环境变量的方式一样,编辑~/.bash_profile文件('~'指的是用户登录后的默认目录),添加一行:export LANG="en_US.UTF-8"
保存退出后重新打开命令行控制台(2)使用PYTHONIOENCODING
在运行python命令前添加参数 PYTHONIOENCODING=utf-8 python printcn.py 该参数的解释可查看官方文档:https://docs.python.org/3.6/using/cmdline.html#envvar-PYTHONIOENCODING (3)重新定义标准输出在代码中添加 sys.stdout = codecs.getwriter("utf-8")(sys.stdout.detach()) ,使代码变为:
import sys import codecs sys.stdout = codecs.getwriter("utf-8")(sys.stdout.detach()) print('中文')