24
votes

Is there any universal method to detect the OS default language? (regardless what is the OS that is running the code)

import os
os.getenv('LANG')

The above code works under Linux, does it work under other OS?

3

3 Answers

31
votes

You could use the getdefaultlocale function in the locale module. It returns the language code and encoding of the system default locale in a tuple:

>>> import locale
>>> locale.getdefaultlocale()
('en_GB', 'cp1252')
36
votes

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
-1
votes

Better use windows command line...

import os

current_locale = os.popen('systeminfo | findstr /B /C:"System Locale"').read()

see https://www.tenforums.com/tutorials/132175-see-current-system-locale-windows-10-a.html