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.)
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With