翻译 argparse 的内部字符串

Translate argparse's internal strings

如何翻译 Python 的 argparse 模块字符串?

例如,当你显示帮助时,它说 "usage: ",这是一个可翻译的字符串,但我不知道如何在我的程序中做到这一点。

这是argparse.py的源代码部分:

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

我无法追踪设置此前缀的方法,我认为这是内部的。

我不想将 .mo 文件附加到系统中的某个位置。理想情况下,翻译应该放在我的程序目录中,或者最好放在源代码中。

如有任何帮助,我们将不胜感激。

运行 以下:

import argparse

class MyHelpFormatter(argparse.HelpFormatter):
    def __init__(self, *args, **kwargs):
        super(MyHelpFormatter, self).__init__(*args, **kwargs)

    def _format_usage(self, usage, actions, groups, prefix):
        return super(MyHelpFormatter, self)._format_usage(
            usage, actions, groups, prefix if prefix else "bla: ")

class MyArgumentParser(argparse.ArgumentParser):
    def __init__(self, *args, **kwargs):
        kwargs['formatter_class']=MyHelpFormatter
        super(MyArgumentParser, self).__init__(*args, **kwargs)


p = MyArgumentParser(description='Foo')
p.add_argument('foo', type=str)
print p.parse_args()

打印

python myargparse.py  --help
bla: myargparse.py [-h] foo

Foo

positional arguments:
  foo

optional arguments:
  -h, --help  show this help message and exit

_('usage: ') 引用 gettext。在 argparse.py 中,在顶部,您有:

from gettext import gettext as _

你可以用 gettext 弄点儿东西。

给定一个 .po 文件:

msgid "usage: "
msgstr "foobar: "

您可以将其转换为 .mo 文件(例如 here)。

之后(其中 ./foo/LC_MESSAGES/messages.mo 是编译 .po 的结果):

~/Desktop> find . -name *mo
./foo/LC_MESSAGES/messages.mo
~/Desktop> cat myargparse2.py
import argparse
import gettext
gettext.bindtextdomain(gettext.textdomain(), '.')
p = argparse.ArgumentParser(description='Foo')
p.add_argument('foo', type=str)
print p.parse_args()
~/Desktop> LANGUAGE=foo python myargparse2.py
foobar: myargparse2.py [-h] foo
myargparse2.py: error: too few arguments

使用您想要的语言而不是 foo

根据 Vlad 的回答,我缩短了它:

class CustomHelpFormatter(argparse.HelpFormatter):
    def __init__(self, *args, **kwargs):
        super(CustomHelpFormatter, self).__init__(*args, **kwargs)

    def _format_usage(self, usage, actions, groups, prefix):
        return super(CustomHelpFormatter, self)._format_usage(
            usage, actions, groups, prefix if prefix else "Uso: ")


if __name__ == "__main__":

    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=CustomHelpFormatter)