Python argparse: name parameters

Question:

I’m writing a program that use argparse, for parsing some arguments that I need.

for now I have this:

parser.add_argument('--rename', type=str, nargs=2, help='some help')

when I run this script I see this:

optional arguments:
  -h, --help            show this help message and exit
  --rename RENAME RENAME
                        some help

How can I change my code in that way that the help “page” will show me:

--rename OLDFILE NEWFILE

Can I then use OLDFILE and NEWFILE value in this way?

args.rename.oldfile
args.rename.newfile
Asked By: Wolfy

||

Answers:

If you set metavar=('OLDFILE', 'NEWFILE'):

import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--rename', type=str, nargs=2, help='some help',
                    metavar=('OLDFILE', 'NEWFILE'))
args = parser.parse_args()
print(args)

Then test.py -h yields

usage: test.py [-h] [--rename OLDFILE NEWFILE]

optional arguments:
  -h, --help            show this help message and exit
  --rename OLDFILE NEWFILE
                        some help

You can then access the arguments with

oldfile, newfile = args.rename

If you really want to access the oldfile with args.rename.oldfile
you could set up a custom action:

import argparse
class RenameAction(argparse.Action):
    def __call__(self, parser, namespace, values, option_string=None):
        setattr(namespace, self.dest,
                argparse.Namespace(
                    **dict(zip(('oldfile', 'newfile'),
                               values))))

parser = argparse.ArgumentParser()
parser.add_argument('--rename', type=str, nargs=2, help='some help',
                    metavar=('OLDFILE', 'NEWFILE'),
                    action=RenameAction)
args = parser.parse_args()

print(args.rename.oldfile)

but it extra code does not really seem worth it to me.

Answered By: unutbu

Read the argparse documentation (http://docs.python.org/2.7/library/argparse.html#metavar):

Different values of nargs may cause the metavar to be used multiple times. Providing a tuple to metavar specifies a different display for each of the arguments:

>>> parser = argparse.ArgumentParser(prog='PROG')
>>> parser.add_argument('-x', nargs=2)
>>> parser.add_argument('--foo', nargs=2, metavar=('bar', 'baz'))
>>> parser.print_help()
usage: PROG [-h] [-x X X] [--foo bar baz]

optional arguments:
 -h, --help     show this help message and exit
 -x X X
 --foo bar baz
Answered By: njzk2
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.