Does python have any way to easily and quickly开发者_Python百科 make CLI utilities without lots of argument parsing boilerplate?
In Perl 6, 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)
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
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.
Simon Willison's optfunc
module tries to provide the functionality you're looking for.
The opterator
module handles this.
https://github.com/buchuki/opterator
Python has the getopts module for doing this.
Recently I came across the begins project for decorating and simplifying command line handling.
It seems to offer a lot of the same functions you are looking for.
精彩评论