How to make python argparse generate non-english text?


The argparse module "automatically generates help and usage messages". I can give Non-English names to the arguments and provide Non-English help texts; but the help output then becomes a mixture of at least two languages, because terms like usage, positional arguments, optional arguments and show this help message and exit are automatically generated in English.

How can I replace this English output with translations?

Preferably, I would like to provide the translations within the script, so that the script generates the same output wherever it is started.

Edit: Based on the answer by Jon-Eric, here an example with his solution:

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()
Argumente = Parser.parse_args()


saved as gives with python3 -h the following help output:

Verwendung: [-h] Eingabe

positional arguments:

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

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

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 -h USAGE: [-h] [-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.