在 Windows 上设置 Python 的语言环境的正确方法是什么?

我试图以区域设置感知的方式对字符串列表进行排序。我使用 Babel 库处理其他与 i18n 相关的任务,但它不支持排序。Python 的 locale模块提供了一个 strcoll函数,但是需要将进程的地区设置为我想要使用的地区。有点痛,但我能忍受。

问题是我似乎不能真正设置地区。locale模块的 文件给出了这个例子:

import locale
locale.setlocale(locale.LC_ALL, 'de_DE')

当我运行它的时候,我得到了这个:

Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python26\Lib\locale.py", line 494, in setlocale
locale.Error: unsupported locale setting

我做错了什么?

119137 次浏览

It seems you're using Windows. The locale strings are different there. Take a more precise look at the doc:

locale.setlocale(locale.LC_ALL, 'de_DE') # use German locale; name might vary with platform

On Windows, I think it would be something like:

locale.setlocale(locale.LC_ALL, 'deu_deu')

MSDN has a list of language strings and of country/region strings

You should not pass an explicit locale to setlocale, it is wrong. Let it find out from the environment. You have to pass it an empty string

import locale
locale.setlocale(locale.LC_ALL, '')

From locale.setlocale docs:

locale.setlocale(category, locale=None):
"""
Set the locale for the given category.  The locale can be
a string, an iterable of two strings (language code and encoding),
or None.
""""

Under Linux (especially Ubuntu) you can either use

locale.setlocale(locale.LC_ALL, 'de_DE.UTF-8')

or

locale.setlocale(locale.LC_ALL, ('de', 'utf-8'))

You will get the same error if the locale is not installed on the system. So, make sure you have the locale installed on your system:

$ locale -a # to list the currently installed locales
$ (sudo) locale-gen de_DE.UTF-8 # to install new locale

Ubuntu

On Ubuntu you may have this problem because you don't have that local installed on your system.

From shell try a:

$> locale -a

and check if you find the locale you are interested in. Otherwise you have to install it:

$> sudo apt-get install language-pack-XXX

where XXX is your language (in my case "xxx = it" , italian locale) Then run a dpkg-reconfigure:

$> sudo dpkg-reconfigure locales

After that try again in your python shell:

>>> import locale
>>> locale.setlocale(locale.LC_ALL,'it_IT.UTF-8')

(this is for italian locale, which was what I needed)

This is the only correct way to use it, providing an example for the German locale:

import locale


locale.setlocale(
category=locale.LC_ALL,
locale="German"  # Note: do not use "de_DE" as it doesn't work
)

I know this has been asked years ago, but I thought I'd try adding what I found out, using Python 3.6 on Windows:

import locale
for x in locale.windows_locale.values():
print(x.replace('_','-'))

I tried some and that also seems to be a way of finding out, what's available on Windows.

Good to know: This for some reason is not compatible to strptime() at the current stable version of Python

And then you simply set the locale:

locale.setlocale(locale.LC_ALL, any_item_of_the_printed_strings)