How to make python's argparse generate Non-English text?
argparse
uses the gettext
API inspired by GNU gettext.
You can use this API to integrate your translation of argparse
in a relatively clean manner.
To do so, call the following code before argparse
outputs any text (but possibly after import argparse
):
import gettext
# Use values that suit your project instead of 'argparse' and 'path/to/locale'
gettext.bindtextdomain('argparse', 'path/to/locale')
gettext.textdomain('argparse')
In order for this solution to work, your translation of argparse
must be located at path/to/locale/ll/LC_MESSAGES/argparse.mo
where ll
is the code of the current language (for example de
; can be configured for example by setting the environment variable LANGUAGE
).
How do you generate the .mo
file?
pygettext --default-domain=argparse /usr/local/lib/python3.5/argparse.py
- Use the actual location of
argparse.py
- Creates the file
argparse.pot
- Use the actual location of
cp argparse.pot argparse-ll.po
- Use an actual language code instead of
ll
- Use an actual language code instead of
- Fill in the missing translation strings in
argparse-ll.po
msgfmt argparse-ll.po -o locale/ll/LC_MESSAGES/argparse.mo
See gettext
documentation for details about creating .mo
file.
I have published these instructions in more detail in README.md of my Czech translation of argparse
.
One way, from this post by Peter Otten:
I don't know much about gettext, but the following suggests that most strings in argparse are properly wrapped:
$ cat localize_argparse.py import gettext def my_gettext(s): return s.upper() gettext.gettext = my_gettext import argparse if __name__ == "__main__": parser = argparse.ArgumentParser() parser.add_argument("-V", action="version") args = parser.parse_args() $ python localize_argparse.py -h USAGE: localize_argparse.py [-h] [-V] OPTIONAL ARGUMENTS: -h, --help SHOW THIS HELP MESSAGE AND EXIT -V show program's version number and exit
The workaround for the "-V" option would be to add the help message explicitly
parser.add_argument("-V", ..., help=_("show..."))
You still have to provide all translations yourself.
Here is a solution with French translation, where one creates a conversion dict that holds the translation for the encountered English keywords
def convertArgparseMessages(s):
subDict = \
{'positional arguments':'Arguments positionnels',
'optional arguments':'Arguments optionnels',
'show this help message and exit':'Affiche ce message et quitte'}
if s in subDict:
s = subDict[s]
return s
gettext.gettext = convertArgparseMessages
import argparse