JorgeeFG JorgeeFG - 4 years ago 219
Python Question

Translate argparse's internal strings

How can I translate Python's argparse module strings?

For example, when you display the help, it says

"usage: "
, string that is translatable but I don't know how to do it in my program.

This is the source code part of

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

I couldn't trace the way to set this prefix, I think this is internal.

I don't want to have to append a .mo file to somewhere in the system. Ideally the translation should live in my program directory, or better in the source code.

Any help would be much appreciated.

Answer Source

Running the following:

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):
        super(MyArgumentParser, self).__init__(*args, **kwargs)

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


python  --help
bla: [-h] foo


positional arguments:

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

_('usage: ') references gettext. In, at the top, you have:

from gettext import gettext as _

You can muck around with gettext a bit.

Given a .po file:

msgid "usage: "
msgstr "foobar: "

You can convert it to a .mo file (for example here).

Afterwards (where ./foo/LC_MESSAGES/ is the result of compiling the .po):

~/Desktop> find . -name *mo
~/Desktop> cat
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
foobar: [-h] foo error: too few arguments

Use your desired languages instead of foo.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download