How to detect the OS default language in python?

Please, you cannot trust locale module for detecting the OS language !!!

Whoever used this information without verifying before, will have a program failing over the world, with those users whose OS language is not the same as the region language.

They are different, (1)the OS language and (2)the localization info.

MSDN states that “A locale ID reflects the local conventions and language for a particular geographical region.”, http://msdn.microsoft.com/en-us/library/8w60z792.aspx

and python docs,

“The POSIX locale mechanism allows programmers to deal with certain cultural issues in an application, without requiring the programmer to know all the specifics of each country where the software is executed.” https://docs.python.org/2/library/locale.html

My Windows7 is in English. But I’m living in Spain so… my locale is ‘es_ES’.. not ‘en_EN’

I don’t know a cross-platform way, for linux you’ve got it. For windows I’ll give you:

Another post talks about using win32 GetSystemDefaultUILanguage, Find out the language windows was installed as.

But if you want getting the windows language identifier, i recommend to use instead GetUserDefaultUILanguage(), because as stated en MSDN, will search recursively until reaches the language:

“Returns the language identifier for the user UI language for the current user. If the current user has not set a language, GetUserDefaultUILanguage returns the preferred language set for the system. If there is no preferred language set for the system, then the system default UI language (also known as “install language”) is returned. For more information about the user UI language, see User Interface Language Management.”

Code:

>>> import locale
>>> locale.getdefaultlocale()
('es_ES', 'cp1252')            # <------------- Bad! I'm on english OS.

>>> import ctypes
>>> windll = ctypes.windll.kernel32
>>> windll.GetUserDefaultUILanguage()
1033
>>> locale.windows_locale[ windll.GetUserDefaultUILanguage() ]
'en_US'          # <----------- Good work

Leave a Comment