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
argparse.py
:

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):
        kwargs['formatter_class']=MyHelpFormatter
        super(MyArgumentParser, self).__init__(*args, **kwargs)


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

prints

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

Foo

positional arguments:
  foo

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

_('usage: ') references gettext. In argparse.py, 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/messages.mo is the result of compiling the .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

Use your desired languages instead of foo.

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