python sys.setdefaultencoding的一点小魔法

python中调用sys.setdefaultencoding方法可以修改默认编码。

但是这个方法调用有一些特别。在python解释器中执行:

>>> import sys
>>> dir(sys)

输出为:

['__displayhook__', '__doc__', '__egginsert', '__excepthook__', '__name__', '__p
ackage__', '__plen', '__stderr__', '__stdin__', '__stdout__', '_clear_type_cache
', '_current_frames', '_getframe', '_mercurial', 'api_version', 'argv', 'builtin
_module_names', 'byteorder', 'call_tracing', 'callstats', 'copyright', 'displayh
ook', 'dllhandle', 'dont_write_bytecode', 'exc_clear', 'exc_info', 'exc_type', '
excepthook', 'exec_prefix', 'executable', 'exit', 'flags', 'float_info', 'float_
repr_style', 'getcheckinterval', 'getdefaultencoding', 'getfilesystemencoding',
'getprofile', 'getrecursionlimit', 'getrefcount', 'getsizeof', 'gettrace', 'getw
indowsversion', 'hexversion', 'long_info', 'maxint', 'maxsize', 'maxunicode', 'm
eta_path', 'modules', 'path', 'path_hooks', 'path_importer_cache', 'platform', '
prefix', 'ps1', 'ps2', 'py3kwarning', 'setcheckinterval', 'setprofile', 'setrecu
rsionlimit', 'settrace', 'stderr', 'stdin', 'stdout', 'subversion', 'version', '
version_info', 'warnoptions', 'winver']

会看到实际上sys模块中并没有这个所谓的setdefaultencoding方法。

文档中描述为:这个方法是为site模块的调用而准备的,而一旦被调用之后,它将会被从sys的名称空间中抹掉。

This function is only intended to be used by the site module 
implementation and, where needed, by sitecustomize. Once used 
by the site module, it is removed from the sys module’s namespace.

而如果确实有需要调用这个方法,可以使用reload再次导入这个模块:

import sys  

print 'old encoding value:', sys.getdefaultencoding()
reload(sys)
sys.setdefaultencoding('utf8')
print 'new encoding value:', sys.getdefaultencoding()

输出为:

old encoding value: ascii
new encoding value: utf8

发表回复

您的电子邮箱地址不会被公开。 必填项已用*标注