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?