Python - default locale is not working

6,252

Normally you should not set LC_ALL persistently as a global environment variable. If you do that on a desktop, you make the GUIs for setting languages/locales useless.

As regards your Python program, you need this line:

locale.setlocale(locale.LC_ALL, '')

It makes the locale, i.e. the output of the locale command, effective within the Python program.

Share:
6,252

Related videos on Youtube

Manuel
Author by

Manuel

Updated on September 18, 2022

Comments

  • Manuel
    Manuel over 1 year

    This is the situation:

    In [1]: import datetime
    
    In [2]: import locale
    
    In [3]: locale.getlocale()
    Out[3]: ('es_ES', 'UTF-8')
    
    In [4]: locale.getdefaultlocale()
    Out[4]: ('es_ES', 'UTF-8')
    
    In [5]: datetime.datetime.strftime(datetime.datetime.today(), '%B')
    Out[5]: 'July'
    

    But the output should be julio

    If I set the locale, then it works

    In [6]: locale.setlocale(locale.LC_ALL, 'es_ES.UTF8')
    Out[6]: 'es_ES.UTF8'
    
    In [7]: datetime.datetime.strftime(datetime.datetime.today(), '%B')
    Out[7]: 'julio'
    

    It happens both in Python2 (2.7.10) and Python3 (3.5.0+)

    The system locale is set to Spanish

    LANG=es_ES.UTF-8
    LANGUAGE=
    LC_CTYPE="es_ES.UTF-8"
    LC_NUMERIC=es_ES.UTF-8
    LC_TIME=es_ES.UTF-8
    LC_COLLATE="es_ES.UTF-8"
    LC_MONETARY=es_ES.UTF-8
    LC_MESSAGES="es_ES.UTF-8"
    LC_PAPER=es_ES.UTF-8
    LC_NAME=es_ES.UTF-8
    LC_ADDRESS=es_ES.UTF-8
    LC_TELEPHONE=es_ES.UTF-8
    LC_MEASUREMENT=es_ES.UTF-8
    LC_IDENTIFICATION=es_ES.UTF-8
    LC_ALL=
    

    EDIT:

    Seeing the locale output, I realised that LC_ALL was not set. I checked /etc/default/locale as it is suggested here and I found a mixture of locales.

    LANG="es_ES.UTF-8"
    LC_ALL=
    LC_NUMERIC="nl_NL.UTF-8"
    LC_TIME="nl_NL.UTF-8"
    LC_MONETARY="nl_NL.UTF-8"
    LC_PAPER="nl_NL.UTF-8"
    LC_NAME="nl_NL.UTF-8"
    LC_ADDRESS="nl_NL.UTF-8"
    LC_TELEPHONE="nl_NL.UTF-8"
    LC_MEASUREMENT="nl_NL.UTF-8"
    LC_IDENTIFICATION="nl_NL.UTF-8"
    

    Maybe because I updated from 15.04 to 15.10?. Anyway, I filled LC_ALL and changed the rest of variables to es_ES, executing again locale-gen as root. However, even after reboot the system, the situation is the same.

  • Manuel
    Manuel almost 8 years
    The thing is that I am using a program (not written by me) that uses the locale module. However, when it prints information, it does not use the appropriate locale. Checking what could been happening, I discovered the issue I am describing.
  • Gunnar Hjalmarsson
    Gunnar Hjalmarsson almost 8 years
    @Manuel: Well, whoever wrote the program, it probably misses the line I suggested.