今天把Mac系统语言改成了英文,打开终端时powerline就非常悲剧地出现了一大串报错
根据图上的信息,powerline调用的python3在解析localename(语言环境)时失败了,也就是字符集的问题。
解析localename的源码如下。
def _parse_localename(localename):
""" Parses the locale code for localename and returns the
result as tuple (language code, encoding).
The localename is normalized and passed through the locale
alias engine. A ValueError is raised in case the locale name
cannot be parsed.
The language code corresponds to RFC 1766. code and encoding
can be None in case the values cannot be determined or are
unknown to this implementation.
"""
code = normalize(localename)
if '@' in code:
# Deal with locale modifiers
code, modifier = code.split('@', 1)
if modifier == 'euro' and '.' not in code:
# Assume Latin-9 for @euro locales. This is bogus,
# since some systems may use other encodings for these
# locales. Also, we ignore other modifiers.
return code, 'iso-8859-15'
if '.' in code:
return tuple(code.split('.')[:2])
elif code == 'C':
return None, None
raise ValueError('unknown locale: %s' % localename)
如果不作任何处理,上述代码就会抛出ValueError的异常。在终端里抛出的localname为UTF-8。然而localename的命名是有地区+语言+字符集。很明显,获取的localname没有地区和语言参数。
并且可以推测,由于解析localname的包是python3自带的,大概在任何python项目里使用此方法也会出现这个问题。
解决:我查看了一下系统的地区为China为默认值。改成了US之后,就没有出现localname的解析问题了。
因为对localname并不是非常了解,了解其原理需参考其他对locale详解的文章。