开发者

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

开发者 https://www.devze.com 2023-03-20 18:52 出处:网络
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 S

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?


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


Here are a couple basic argparse resources I dug up:

Some slides on argparse: http://www.slideshare.net/tisto/argparse-python-command-line-parser

A little argparse example: http://www.rutherfurd.net/tag/argparse/

Here is a real-world argparse example: https://github.com/harijay/xtaltools/blob/e683fcef6a5ad7394b87382e58d4dce32a85585b/maskconvert.py

As far as avoiding pitfalls, here is a nice looking wrapper for argparse to reduce the boilerplate code you have to write for some common usecases: http://travelingfrontiers.wordpress.com/2010/11/03/simple-python-argparse-wrapper/

0

精彩评论

暂无评论...
验证码 换一张
取 消