Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I find all available locales in Python

Tags:

python

locale

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.)

like image 1000
pst Avatar asked Nov 15 '18 13:11

pst


People also ask

What is en_US?

For example, an English-speaking user in the United States can select the en_US. UTF-8 locale (English for the United States), while an English-speaking user in Great Britain can select en_GB. UTF-8 (English for Great Britain).


1 Answers

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.

like image 68
pst Avatar answered Nov 15 '22 00:11

pst