Mar-17-2019, 06:02 AM
Here are my tries to work with locale and gettext.
In other words: It's pain in the a....
In other words: It's pain in the a....
from pathlib import Path import locale from locale import ( LC_ALL, LC_NUMERIC, setlocale, getlocale, getdefaultlocale, currency ) from locale import format_string as lformat import gettext def translations(domain, localedir): localedir = Path(localedir) result = {} for trans in localedir.glob(f'**/{domain}.mo'): lang = trans.parent.parent.name print(f'Found translation {trans}. Language: {lang}') try: result[lang] = gettext.translation(domain, localedir, [lang]) except Exception as e: print(e) print() return result trans = translations('messages', 'translations') def current_setting(): for symbol in dir(locale): if symbol.startswith('LC_') and symbol != 'LC_ALL': tp = getattr(locale, symbol) print(f'{symbol:<20}{locale.getlocale(tp)}') print() def test(): current_setting() try: print(currency(val)) except ValueError as e: print(e) print(lformat('%.2f', val, grouping=True)) print(_('Hello World!')) print() val = 1337.42 defaultlocale = getdefaultlocale() print('Defaultlocale is', defaultlocale) print() setlocale(LC_ALL, 'en_US.utf8') trans['en_US'].install() test() setlocale(LC_ALL, 'en_US.utf8') print('LC_ALL set to en_US.utf8') trans['en_GB'].install() test() trans['de_DE'].install() ret = setlocale(LC_ALL, defaultlocale) print('LC_ALL set to', ret) test()Output
Output:Found translation translations/en_US/LC_MESSAGES/messages.mo. Language: en_US
Found translation translations/en_GB/LC_MESSAGES/messages.mo. Language: en_GB
Found translation translations/de_DE/LC_MESSAGES/messages.mo. Language: de_DE
Defaultlocale is ('de_DE', 'UTF-8')
LC_COLLATE ('en_US', 'UTF-8')
LC_CTYPE ('en_US', 'UTF-8')
LC_MESSAGES ('en_US', 'UTF-8')
LC_MONETARY ('en_US', 'UTF-8')
LC_NUMERIC ('en_US', 'UTF-8')
LC_TIME ('en_US', 'UTF-8')
$1337.42
1,337.42
Fuck You!
LC_ALL set to en_US.utf8
LC_COLLATE ('en_US', 'UTF-8')
LC_CTYPE ('en_US', 'UTF-8')
LC_MESSAGES ('en_US', 'UTF-8')
LC_MONETARY ('en_US', 'UTF-8')
LC_NUMERIC ('en_US', 'UTF-8')
LC_TIME ('en_US', 'UTF-8')
$1337.42
1,337.42
Hello World!
LC_ALL set to de_DE.UTF-8
LC_COLLATE ('de_DE', 'UTF-8')
LC_CTYPE ('de_DE', 'UTF-8')
LC_MESSAGES ('de_DE', 'UTF-8')
LC_MONETARY ('de_DE', 'UTF-8')
LC_NUMERIC ('de_DE', 'UTF-8')
LC_TIME ('de_DE', 'UTF-8')
1337,42 €
1.337,42
Hallo Welt!
I could not test with locale en_GB, because I haven't installed it on my system.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
All humans together. We don't need politicians!