views:

143

answers:

4

Does python have any way to easily and quickly make CLI utilities without lots of argument parsing boilerplate?

In perl6, the signature for the MAIN sub automagically parses command line arguments.

Is there any way to do something similar in python without lots of boilerplate? If there is not, what would be the best way to do it? I'm thinking a function decorator that will perform some introspection and do the right thing. If there's nothing already like it, I'm thinking something like what I have below. Is this a good idea?

@MagicMain
def main(one, two=None, *args, **kwargs):
    print one # Either --one or first non-dash argument
    print two # Optional --arg with default value (None)
    print args # Any other non-dash arguments
    print kwargs # Any other --arguments

if __name__ == '__main__':
    main(sys.argv)
A: 

Python has the getopts module for doing this.

JoshD
+2  A: 

I'm not really sure what you consider to be parsing boilerplate. The 'current' approach is to use the argparse system for python. The older system is getopt.

jkerian
`argparse` seems like it could be good under the hood of a decorator like I describe... It could remove all the `parser.add_argument` boilerplate.
Daenyth
+1  A: 

Simon Willison's optfunc module tries to provide the functionality you're looking for.

Will McCutchen
This looks very promising.
Daenyth
+2  A: 

The Baker library contains some convenient decorators to "automagically" create arg parsers from method signatures.

For example:

@baker.command
def test(start, end=None, sortby="time"):
  print "start=", start, "end=", end, "sort=", sortby

$ script.py --sortby name 1
start= 1 end= sortby= name
Ben James
That's pretty much exactly what I imagined. I'll look into it and leave a green cookie for you when I do :)
Daenyth