首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >为什么我们不应该在py脚本中使用sys.setdefaultencoding("utf-8")呢?

为什么我们不应该在py脚本中使用sys.setdefaultencoding("utf-8")呢?
EN

Stack Overflow用户
提问于 2010-09-30 15:46:09
回答 1查看 219.4K关注 0票数 185

我见过几个py脚本在脚本的顶部使用了这个。在什么情况下应该使用它?

import sys
reload(sys)
sys.setdefaultencoding("utf-8")
EN

回答 1

Stack Overflow用户

发布于 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

将会起作用

票数 19
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/3828723

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档