Python 3 gettext not working for argparse

心已入冬 提交于 2019-12-12 03:57:22

问题


I want to translate 'usage: ' into 'foobar'.

    print(gettext.find('test', 'i18n', ['en_US']))
    translator = gettext.translation('test', localedir='i18n', languages=['en_US'])
    translator.install()
    print(_('usage: '))
    parser = argparse.ArgumentParser(prog="jcheq.py",
                                     usage="%(prog)s [opciones] [paths...]\nThe paths are optional; if not given . is "
                                           "used.",
                                     add_help=False,
                                     formatter_class=argparse.ArgumentDefaultsHelpFormatter)

But it outputs this:

~/Desktop/Proyectos/UNPAZ/jcheq/jcheq$ python3 jcheq.py --help
i18n/en_US/LC_MESSAGES/test.mo
foobar: 
usage: jcheq.py [opciones] [paths...]
The paths are optional; if not given . is used.

Opciones:
  -h, --help      Mostrar este mensaje de ayuda y salir.
  -m, --modified  show last modified date/time (default: False)

Seems that it is working for my string, but not for argparse's one:

argparse.py:292 aprox

 def _format_usage(self, usage, actions, groups, prefix):
        if prefix is None:
            prefix = _('usage: ')

回答1:


Borrowing from How to make python's argparse generate Non-English text?

import gettext

def Übersetzung(Text):
    Text = Text.replace("usage", "Verwendung")
    Text = Text.replace("show this help message and exit",
                        "zeige diese Hilfe an und tue nichts weiteres")
    Text = Text.replace("error:", "Fehler:")
    Text = Text.replace("the following arguments are required:",
                        "Die folgenden Argumente müssen angegeben werden:")
    return Text
gettext.gettext = Übersetzung

import argparse    
parser = argparse.ArgumentParser(prog="jcheq.py",
            usage="%(prog)s [opciones] [paths...]\nThe paths are optional; if not given . is "
                    "used.")
parser.print_usage()
print()
parser.print_help()

produces:

1702:~/mypy$ python3 stack35347168.py 
Verwendung: jcheq.py [opciones] [paths...]
The paths are optional; if not given . is used.

Verwendung: jcheq.py [opciones] [paths...]
The paths are optional; if not given . is used.

optional arguments:
  -h, --help  zeige diese Hilfe an und tue nichts weiteres


来源:https://stackoverflow.com/questions/35347168/python-3-gettext-not-working-for-argparse

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!