Is it possible to translate the own messages of argparse?

0

I have several command-line python scripts that handle several parameters to invoke them, this I resolve through argparse , which is very simple, however this library has some messages in English (at least in python 3.4) that I would like to translate, let's see an example:

# -*- coding: utf-8 -*-
import argparse

def init_argparse():
    cmdparser = argparse.ArgumentParser(prog='programa', description='descripcion')
    cmdparser.add_argument('archivo', type=str, nargs='?', help="Archivo de input", metavar="\"archivo a interpretar\"")
    cmdparser.add_argument("-v", "--version", action='version', help="mostrar la versión y salir", version="1.1.1")
    return cmdparser

if __name__ == "__main__":

    cmdparser = init_argparse()
    try:
        args = cmdparser.parse_args()
    except IOError as msg:
        cmdparser.error(str(msg))
        sys.exit(-1)

If this Script is executed as python miscript.py --help , I get the following output:

usage: programa [-h] [-v] ["archivo a interpretar"]

descripcion

positional arguments:
  "archivo a interpretar"
                        Archivo de input

optional arguments:
  -h, --help            show this help message and exit
  -v, --version         mostrar la versión y salir

As you can see there are texts like "usage", "positional arguments", "optional arguments" and others that are in English. How can I translate them so that the interface is consistent?

    
asked by Patricio Moracho 05.05.2017 в 17:45
source

1 answer

2

I do not know if it is the best solution, but I could solve it in the following way:

  • First you have to import gettext , the multilanguage service of python
  • Then you have to create your own translation routine, for example: my_gettext and set the same in gettext.gettext = my_gettext . With this we can control the translation process of the chains, previously we must investigate which chains are the ones that we are going to translate, some are "fstrings" type.
  • The routine my_gettext should check the strings that are requested to translate and we should replace them with the versions that we want
  • All this must be done before importing argparse , also do not forget to make sure that the file is in utf-8, this way it would end up being our example:

    # -*- coding: utf-8 -*-
    
    import gettext
    
    def my_gettext(s):
      """my_gettext: Traducir algunas cadenas de argparse."""
      current_dict = {
                  'usage: ': 'uso: ',
                  'optional arguments': 'argumentos opcionales',
                  'show this help message and exit': 'mostrar esta ayuda y salir',
                  'positional arguments': 'argumentos posicionales',
                  'the following arguments are required: %s': 'los siguientes argumentos son requeridos: %s',
                  'show program''s version number and exit': 'Mostrar la versión del programa y salir',
                  'expected one argument': 'se espera un valor para el parámetro',
                  'expected at least one argument': 'se espera al menos un valor para el parámetro'
      }
      print(s)
      if s in current_dict:
          return current_dict[s]
      return s
    
    #gettext.gettext = my_gettext
    
    import argparse
    
    def init_argparse():
        cmdparser = argparse.ArgumentParser(prog='programa', description='descripcion')
        cmdparser.add_argument('archivo',type=str, nargs='?', help="Archivo de input", metavar="\"archivo a interpretar\"")
        cmdparser.add_argument("-v", "--version",action='version', help="mostrar la versión y salir", version="1.1.1")
        return cmdparser
    
    if __name__ == "__main__":
    
        cmdparser = init_argparse()
        try:
            args = cmdparser.parse_args()
        except IOError as msg:
            cmdparser.error(str(msg))
            sys.exit(-1)
    

    The exit, now it is more consistent:

    uso: programa [-h] [-v] ["archivo a interpretar"]
    
    descripcion
    
    argumentos posicionales:
      "archivo a interpretar"
                            Archivo de input
    
    argumentos opcionales:
      -h, --help            mostrar esta ayuda y salir
      -v, --version         mostrar la versión y salir
    
        
    answered by 05.05.2017 / 17:45
    source