Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

How to Customize the New 2.7 ArgumentParser Library Class (module argparse)?

0 views
Skip to first unread message

Tom Browder

unread,
Aug 20, 2010, 3:32:54 PM8/20/10
to pytho...@python.org
I have converted from OptionParser to ArgumentParser (new in version
2.7) to great advantage, and I think it's a great improvement! But
now I want to customize the help formatting just a bit.

The documentation is sketchy here, but I started by subclassing
ArgumentParser and attempted to redefine format_usage, but after
looking at the detailed instructions with pydoc I see "the API of the
formatter objects is still considered an implementation detail."

I take that to mean I should abandon such efforts at the moment.

So, using the defined class as is, and following instructions in the
online docs, I have been able to get my output to look like this:

==============>
$ test_argparser.py -h
usage: test_argparser.py [options]

A program to manipulate user programs.

optional arguments:
-h, --help Show this help message and exit.
-v, --version Show program's version number and exit.
-s, --show Show a list of user post-processing programs.

Version 2010-08-20.01
<==============

To beautify things I would like to change two strings which are
auto-generated by the standard parser:

1. change "usage:"

to "Usage:" # capitalize 'usage'

2. change "optional arguments:"

to "Optional arguments:" # capitalize 'Optional'

Does anyone know how to do it without modifying source code?

Thanks,

-Tom

Thomas M. Browder, Jr.
Niceville, Florida
USA

Peter Otten

unread,
Aug 20, 2010, 4:19:42 PM8/20/10
to
Tom Browder wrote:

You can use internationalization via

http://docs.python.org/library/gettext.html

or take a shortcut:

$ cat tmp.py
lookup = {
"usage: ": "Usage: ",
"optional arguments": "Optional arguments"}

def gettext(s):
return lookup.get(s, s)

import argparse
argparse._ = gettext

if __name__ == "__main__":
p = argparse.ArgumentParser()
p.parse_args()

$ python tmp.py -h
Usage: tmp.py [-h]

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

Peter

0 new messages