31

I'm writing a program that uses 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 so that the help will show this?

--rename OLDFILE NEWFILE

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

args.rename.oldfile
args.rename.newfile

2 Answers 2

57

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.

Sign up to request clarification or add additional context in comments.

1 Comment

thanks for all details provided... "oldfile, newfile = args.rename" will do the job :)
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.