我见过几个py脚本在脚本的顶部使用了这个。在什么情况下应该使用它?
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
发布于 2011-07-19 11:40:26
#!/usr/bin/env python
#-*- coding: utf-8 -*-
u = u'moçambique'
print u.encode("utf-8")
print u
chmod +x test.py
./test.py
moçambique
moçambique
./test.py > output.txt
Traceback (most recent call last):
File "./test.py", line 5, in <module>
print u
UnicodeEncodeError: 'ascii' codec can't encode character
u'\xe7' in position 2: ordinal not in range(128)
在shell上,不能发送到sdtout,所以这是一种解决方法,可以写入stdout。
我提出了其他方法,如果未定义sys.stdout.encoding,或者换句话说,需要首先导出PYTHONIOENCODING=UTF-8才能写入标准输出,则不会运行该方法。
import sys
if (sys.stdout.encoding is None):
print >> sys.stderr, "please set python env PYTHONIOENCODING=UTF-8, example: export PYTHONIOENCODING=UTF-8, when write to stdout."
exit(1)
因此,使用相同的示例:
export PYTHONIOENCODING=UTF-8
./test.py > output.txt
将会起作用
https://stackoverflow.com/questions/3828723
复制相似问题