27

I am not sure what optparse's metavar parameter is used for. I see it is used all around, but I can't see its use.

Can someone make it clear to me? Thanks.

bluish
  • 26,356
  • 27
  • 122
  • 180

5 Answers5

31

As @Guillaume says, it's used for generating help. If you want to have an option that takes an argument, such as a filename, you can add the metavar parameter to the add_option call so your preferred argument name/descriptor is output in the help message. From the current module documentation:

usage = "usage: %prog [options] arg1 arg2"
parser = OptionParser(usage=usage)
parser.add_option("-f", "--filename",
                  metavar="FILE", help="write output to FILE"),

would produce help like this:

usage: <yourscript> [options] arg1 arg2

options:
  -f FILE, --filename=FILE

The "FILE" after the "-f" and the "--filename" comes from the metavar.

Blair Conrad
  • 233,004
  • 25
  • 132
  • 111
5

metavar seems to be used for generating help : http://www.python.org/doc/2.5.2/lib/optparse-generating-help.html

Guillaume
  • 18,494
  • 8
  • 53
  • 74
  • metavar="helpfulname" customizes the help message with a helpful name; different from the dest="name". The dest="name" might not be helpful to users. – S.Lott Dec 03 '08 at 12:49
0

There's another meaningful use of metavar where one desires to use 'dest' as the argument lookup-tag but mask the help message by metavar. (E.g. sometimes handy when using subparsers). (As indicated in the comment of S.Lott).

parser.add_argument(
        'my_fancy_tag',
        help='Specify destination',
        metavar='helpful_message'
        )

or equally

parser.add_argument(
        dest='my_fancy_tag',
        help='Specify destination',
        metavar='helpful_message'
        )

Help will show the metavar:

./parse.py -h usage: parser [-h] destination

positional arguments:   
  helpful_message  Specify destination

but dest will store the fancy_tag in Namespace:

./parse.py test 
Namespace(my_fancy_tag='test')
Community
  • 1
  • 1
count0
  • 2,537
  • 2
  • 22
  • 30
0

It's now preferable to use the argparse library instead of optparse.

Reasons why are given here.

Community
  • 1
  • 1
twasbrillig
  • 17,084
  • 9
  • 43
  • 67
0

metavar is a variable used for print in the screen after option. Usually used for suggestion input after option are FILE or INT or STRING to user. Without metavar, optparse will print dest value after option you've been added.

bluish
  • 26,356
  • 27
  • 122
  • 180
Yuda Prawira
  • 12,075
  • 10
  • 46
  • 54