Search code examples
pythoncommand-line-argumentsrakumagic-methodsmethod-signature

Python magical main() signature like Perl 6


Does python have any way to easily and quickly 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)

Solution

  • 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