how to localize python's argparse module, without patching it?

  • Last Update :
  • Techknowledgy :

Usage:

python pygettext.py argparse.py

Suggestion : 2

In a script, parse_args() will typically be called with no arguments, and the ArgumentParser will automatically determine the command-line arguments from sys.argv.,The argparse module makes it easy to write user-friendly command-line interfaces. The program defines what arguments it requires, and argparse will figure out how to parse those out of sys.argv. The argparse module also automatically generates help and usage messages and issues errors when users give the program invalid arguments.,In general, the argparse module assumes that flags like -f and --bar indicate optional arguments, which can always be omitted at the command line. To make an option required, True can be specified for the required= keyword argument to add_argument():,For positional arguments with nargs equal to ? or *, the default value is used when no command-line argument was present:

import argparse

parser = argparse.ArgumentParser(description = 'Process some integers.')
parser.add_argument('integers', metavar = 'N', type = int, nargs = '+',
   help = 'an integer for the accumulator')
parser.add_argument('--sum', dest = 'accumulate', action = 'store_const',
   const = sum,
   default = max,
   help = 'sum the integers (default: find the max)')

args = parser.parse_args()
print(args.accumulate(args.integers))
$ python prog.py - h
usage: prog.py[-h][--sum] N[N...]

Process some integers.

positional arguments:
   N an integer
for the accumulator

options:
   -h, --help show this help message and exit
   --sum sum the integers(
      default: find the max)
$ python prog.py 1 2 3 4
4

$ python prog.py 1 2 3 4--sum
10
$ python prog.py a b c
usage: prog.py[-h][--sum] N[N...]
prog.py: error: argument N: invalid int value: 'a'
>>> parser = argparse.ArgumentParser(description = 'Process some integers.')
>>> parser.add_argument('integers', metavar = 'N', type = int, nargs = '+',
      ...help = 'an integer for the accumulator') >>>
   parser.add_argument('--sum', dest = 'accumulate', action = 'store_const',
      ...
      const = sum,
      default = max,
      ...help = 'sum the integers (default: find the max)')

Suggestion : 3

This issue tracker has been migrated to GitHub, and is currently read-only. For more information, see the GitHub FAQs in the Python's Developer Guide., Help Tracker Documentation Tracker Development Report Tracker Problem

The - deprecated - "version"
keyword
for argparse.ArgumentParser allowed
for localization of the "show program's version number and exit"
help text
for -v / --version(output of "-h" / "--help")

The new version action
for add_argument does not allow this - resulting in a partially translated output
for the - v / --version option.
@Thorsten sorry about the delay involved here.
In this patch I added the '_()'
localization to the '_VersionAction'
default 'help'.

While this is a straight forward change, I haven 't tested it.  It does run test_argparse.py, but that doesn'
t have any tests
for localization.

According to the discussion here:
   https: //mail.python.org/pipermail/python-dev/2010-May/100215.html
   this
default help was originally None, and adding this string was seen
as a worthwhile convenience.Localization was not considered.

Does this use of _() really save the user effort ? May be it would
if they are already using the depricated version.Otherwise they could just give the version argument their own non
default help line.I haven 't used localization enough to know.
I have tested the patch.It fixes the problem
for me.

You are right, new programs would just supply translated help to the version action.No effort would be saved.

But the programs updated from the deprecated syntax may rely on a separate string list
for translating strings found in argparse.py.They would lose the translation
for the "--version"
help without any warning.
Debugging and fixing that would take some effort.
Dear all,

As commented on PR 12711(https: //github.com/python/cpython/pull/12711#pullrequestreview-724899323), there is a slight issue with the proposed patch, as it translates the `--version` help string as soon as the `argparse` module is imported (at which point the programmer might not have correctly initialized the `gettext` global domain yet). The suggested modification of PR 12711 should fix this, so that the translation only happens when an instance of `_VersionAction` is actually created:
      ``
      `
diff a/Lib/argparse.py b/Lib/argparse.py
--- a/Lib/argparse.py
+++ b/Lib/argparse.py
@@ -1042,7 +1042,9 @@ def __init__(self,
                  version=None,
                  dest=SUPPRESS,
                  default=SUPPRESS,
-                 help="show program's version number and exit"):
+                 help=None):
+        if help is None:
+            help = _("show program's version number and exit")
         super(_VersionAction, self).__init__(
             option_strings=option_strings,
             dest=dest,
`
      ``

      However, I 'm not sure I understand correctly Pavel'
      s comment as to why merging this patch would make some old programs lose their translation
      for this string: since `argparse`
      does not itself provide any translation, it is up to the programmers to provide `gettext`
      translations
      for `argparse`
      strings as well.Adding the call to `_()`
      here seems harmless to me:
      -
      if a program already has a `gettext`
      translation string
      for "show program's version number and exit", it will be used, as expected; -
      otherwise,
      if it hasn 't (and relies on other mechanisms to translate this string), the string will remain untranslated, and the "custom" translation mechanisms will be able to process it as before.

      In any
      case, my guess is that localized programs already explicitly pass a localized help string to the `_VersionAction`
      constructor in order to circumvent the nonlocalized
      default help string:
      ``
      `
parser.add_argument('-V', action='version', version='%(prog)s 3.9',
                    help=_("show program's version number and exit"))
`
      ``
      These programs should also remain completely unaffected by this change.

      Thanks!

      Kind regards,
      Jérémie.

Suggestion : 4

This project uses a standard Major.Minor.Patch versioning pattern. Inside a major version, public API stability is expected (at least after 1.0.0 version will be published).,Localization of the Python argparse module,Provides translations for argparse module,The argparse module makes it easy to write user-friendly command-line interfaces. Specifically, it automatically generates help and usage messages and issues errors when users give the program invalid arguments. Unfortunately, even if the module is able to use gettext type localization strings, none is provided by the standard library.

If you want to contribute, you should get a copy of the full tree from GitHUB:

git clone https: //github.com/s-ball/i18nparse.git [your_working_copy_folder]

The i18nparse module defines 2 functions:

def activate(lang = None)

which activates the usage of the translation for the required language. By default, the language for locale.getlocale() is used. Note: In order to use the expected locale, it should be loaded prior to the call to activate with locale.setlocale(locale.LC_ALL, locale_name) where locale_name is the name of a known locale or '' (empty string) for the default locale.

def deactivate()

Assuming a fr_FR locale, this displays:

usage: foo[-h]

arguments optionnels:
   -h, --help affiche ce message et termine le programme

Suggestion : 5

SAXException Objects , Functions and Exceptions , Unicode Exception Objects , Standard Exceptions

$ ls
cpython devguide prog.py pypy rm - unused - function.patch
$ ls pypy
ctypes_configure demo dotviewer include lib_pypy lib - python...
   $ ls - l
total 20
drwxr - xr - x 19 wena wena 4096 Feb 18 18: 51 cpython
drwxr - xr - x 4 wena wena 4096 Feb 8 12: 04 devguide -
   rwxr - xr - x 1 wena wena 535 Feb 19 00: 05 prog.py
drwxr - xr - x 14 wena wena 4096 Feb 7 00: 59 pypy -
   rw - r--r--1 wena wena 741 Feb 18 01: 01 rm - unused - function.patch
$ ls--help
Usage: ls[OPTION]...[FILE]...
   List information about the FILEs(the current directory by
      default).
Sort entries alphabetically
if none of -cftuvSUX nor--sort is specified.
   ...
import argparse
parser = argparse.ArgumentParser()
parser.parse_args()
$ python prog.py
$ python prog.py--help
usage: prog.py[-h]

optional arguments:
   -h, --help show this help message and exit
$ python prog.py--verbose
usage: prog.py[-h]
prog.py: error: unrecognized arguments: --verbose
$ python prog.py foo
usage: prog.py[-h]
prog.py: error: unrecognized arguments: foo
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("echo")
args = parser.parse_args()
print args.echo
$ python prog.py
usage: prog.py[-h] echo
prog.py: error: the following arguments are required: echo
$ python prog.py--help
usage: prog.py[-h] echo

positional arguments:
   echo

optional arguments:
   -h, --help show this help message and exit
$ python prog.py foo
foo
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("echo", help = "echo the string you use here")
args = parser.parse_args()
print args.echo