python locale_python – locale.getpreferredencoding() – 为什么这会重置string.letters?

注意:OP做什么来解决问题是将encoding =’UTF-8’传递给打开的调用。如果你遇到这个问题,只是寻找一个修复这个工作。其余的职位是强调为什么。

怎么了

正如卢卡斯所说,文件指明:

On some systems, it is necessary to invoke setlocale() to obtain the user preferences

最初,string.letters设置为返回小写大写:

lowercase = 'abcdefghijklmnopqrstuvwxyz'

uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'

letters = lowercase + uppercase

但是,当您调用getpreferredencoding()时,_locale模块将通过调用PyDict_SetItemString(string,“letters”,ulo);之后它会在fixup_ulcase(void)内生成它们,具体如下:

/* create letters string */

n = 0;

for (c = 0; c < 256; c++) {

if (isalpha(c))

ul[n++] = c;

}

ulo = PyString_FromStringAndSize((const char *)ul, n);

if (!ulo)

return;

if (string)

PyDict_SetItemString(string, "letters", ulo);

Py_DECREF(ulo);

反过来,这是在PyLocale_setlocale中调用的,它确实是setlocale,由getpreferredencoding调用 – 这里的代码为http://hg.python.org/cpython/file/07a6fca7ff42/Lib/locale.py#l612:

def getpreferredencoding(do_setlocale = True):

"""Return the charset that the user is likely using,

according to the system configuration."""

if do_setlocale:

oldloc = setlocale(LC_CTYPE)

try:

setlocale(LC_CTYPE, "")

except Error:

pass

result = nl_langinfo(CODESET)

setlocale(LC_CTYPE, oldloc)

return result

else:

return nl_langinfo(CODESET)

我该如何避免?

尝试getpreferredencoding(False)

为什么Windows不会发生?

Windows使用不同的代码获取区域设置,您可以看到here。

在Python 3中

在Python 3中,getdefaultlocale不接受布尔setlocale变量,并且不会像here那样调用setlocale本身。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值