Python Glossary Русский

all Python 3gettextfunction

gettext.gettext()

translation functions

Translates a string using the current global domain. Without a catalog it returns the string unchanged.

Syntax

text = gettext.gettext(message, /)

A missing translation is not an error: the function quietly returns the source, so a typo in the key or a forgotten domain binding shows only on screen. Translate the template, not the assembled string: gettext(f'Hi, {name}') finds no key; use gettext('Hi, {name}').format(name=name).

Examples

import gettext
print(gettext.gettext('Hello'))  # → Hello — каталога нет
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, {name}': 'Привет, {name}'}))
os.environ['LANGUAGE'] = 'ru'
gettext.bindtextdomain('app', 'loc')
gettext.textdomain('app')
name = 'Аня'
print(gettext.gettext('Hi, {name}').format(name=name))  # → Привет, Аня
print(gettext.gettext(f'Hi, {name}'))  # → Hi, Аня

See also

Open in the full glossarydocs.python.orgReport an inaccuracy