Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Explanation for argparse python modul behaviour: Where do the capital placeholders come from?

I am trying to write a command line interface (for the first time) and after reading up about argparse, optparse and getopt I chose argparse because of several recommendations here on SO and elswhere in the net. Adapting a little of the advice of Mr. van Rossum I hooked up my first command line interface like this:

def main(argv=None):
    if argv is None:
        argv = sys.argv
    desc = u'some description'
    parser = argparse.ArgumentParser(description=desc)

    parser.add_argument('-s', '--search', help='Search for someone.')
    parser.add_argument('-c', '--do_something_else', help='Do something else.')

    args = parser.parse_args()
    print args

if __name__ == '__main__':
    sys.exit(main())

Doing python myscript.py -h results in:

usage: dblp.py [-h] [-s SEARCH] [-c DO_SOMETHING_ELSE]

some description

optional arguments:
  -h, --help            show this help message and exit
  -s SEARCH, --search SEARCH
                        Search for someone.
  -c DO_SOMETHING_ELSE, --do_something_else DO_SOMETHING_ELSE
                        Do something else.

So my first question is: Why are SEARCH and DO_SOMETHING_ELSE written in CAPITAL LETTERS? The second question would be: Do I break any standards? Is there a better way (ore a nice real world example I can learn from) how to build clean and useful command line interfaces with python? And are there pitfalls one should avoid, when writing cmd interfaces?

like image 531
Aufwind Avatar asked Jan 20 '23 05:01

Aufwind


1 Answers

The capital letter items are just value placeholders; they're taken from the destination of the option. You can specify alternative placeholders via the metavar= param of add_argument:

http://docs.python.org/dev/library/argparse.html#metavar

like image 53
Amber Avatar answered Apr 19 '23 22:04

Amber