9

How can I (on a GNU/Linux system) find all available locales to use with the module locale?

The only thing I find that is close in the the module is the dictionary locale_alias with aliases for locales. That is sometimes mentioned as where to look what locales you have, but it doesn't contain all aliases. On my system this program

#! /usr/bin/python3
import locale
for k, v in sorted(locale.locale_alias.items()):
    if k.startswith('fr_') or v.startswith('fr_'):
        print('{:20}{}'.format(k, v))

prints

c-french            fr_CA.ISO8859-1
fr                  fr_FR.ISO8859-1
fr_be               fr_BE.ISO8859-1
fr_ca               fr_CA.ISO8859-1
fr_ch               fr_CH.ISO8859-1
fr_fr               fr_FR.ISO8859-1
fr_lu               fr_LU.ISO8859-1
français            fr_FR.ISO8859-1
fre_fr              fr_FR.ISO8859-1
french              fr_FR.ISO8859-1
french.iso88591     fr_CH.ISO8859-1
french_france       fr_FR.ISO8859-1

ignoring all utf-8 locales, like 'fr_FR.utf8', which can indeed be used as argument for locale.setlocale. From the shell, locale -a | grep "^fr_.*utf8" gives

fr_BE.utf8
fr_CA.utf8
fr_CH.utf8
fr_FR.utf8
fr_LU.utf8

showing lots of options. (One way is of course to run this shell command from Python, but I would have thought there is a way to do this directly from Python.)

pst
  • 287
  • 2
  • 12
  • Oddly, when I look for `endswith(.utf8)` I find more than the shell. – kabanus Nov 15 '18 at 13:21
  • 1
    `locale_alias` apparently sucks - https://stackoverflow.com/questions/19709026/how-can-i-list-all-available-windows-locales-in-python-console - you are not alone. – kabanus Nov 15 '18 at 13:27
  • `locale_alias` sucks big time ... I just wasted 2 hours on it – Shadi Aug 14 '19 at 16:00

1 Answers1

1

It seems like there is no good way to to this directly from Python, so I'll answer how to run this shell command from Python.

#! /usr/bin/python3
import subprocess

def find_locales():
    out = subprocess.run(['locale', '-a'], stdout=subprocess.PIPE).stdout
    try:
        # Even though I use utf8 on my system output from "locale -a"
        # included "bokmål" in Latin-1. Then this won't work, but the
        # exception will.
        res = out.decode('utf-8')
    except:
        res = out.decode('latin-1')
    return res.rstrip('\n').splitlines()

if __name__ == "__main__":
    for loc in find_locales():
        print(loc)

Note that subprocess.run is new in Python 3.5. For earlier Python versions, see this question on alternative ways to run shell commands.

pst
  • 287
  • 2
  • 12