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

时光总嘲笑我的痴心妄想 提交于 2020-01-21 11:52:11

问题


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?


回答1:


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/




回答2:


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



来源:https://stackoverflow.com/questions/6728019/explanation-for-argparse-python-modul-behaviour-where-do-the-capital-placeholde

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!