Python argparse: name parameters

Wolfy picture Wolfy · Aug 22, 2013 · Viewed 13.2k times · Source

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

Answer

unutbu picture unutbu · Aug 22, 2013

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.