Python Glossary Русский

all Python 3gettextfunction

gettext.find()

translation catalogs

Looks up the .mo file for a domain and a list of languages and returns its path or None. It does not load the catalog.

Syntax

path = gettext.find(domain, localedir=None, languages=None, all=False)

If languages is not given, they come from the LANGUAGE, LC_ALL, LC_MESSAGES and LANG environment variables — the first non-empty one wins, so the result differs between a developer's machine and a server. For 'ru_RU.UTF-8' it also tries the simpler variants down to 'ru'. Not found means None, not an exception.

Examples

import io, struct
def mo(cat):  # собрать каталог .mo в памяти
    cat = {'': 'Content-Type: text/plain; charset=UTF-8\n', **cat}
    ks = sorted(cat)
    bs = [k.encode() for k in ks] + [cat[k].encode() for k in ks]
    n, data, tab = len(ks), b'', b''
    for b in bs:
        tab += struct.pack('<2I', len(b), 28 + 16 * n + len(data))
        data += b + b'\0'
    return struct.pack('<7I', 0x950412de, 0, n, 28, 28 + 8 * n, 0, 0) + tab + data
import gettext
import os
os.makedirs('loc/ru/LC_MESSAGES', exist_ok=True)
open('loc/ru/LC_MESSAGES/app.mo', 'wb').write(mo({'Hi': 'Привет'}))
path = gettext.find('app', 'loc', languages=['ru_RU.UTF-8'])
print(path.replace(os.sep, '/').endswith('loc/ru/LC_MESSAGES/app.mo'))  # → True
print(gettext.find('app', 'loc', languages=['de']))  # → None

See also

Open in the full glossarydocs.python.orgReport an inaccuracy