I’m having a bit of trouble understanding how python argparse works.
My script has three positional arguments that don’t take parameters: make, compile and clean. I’ve done it through subparsers like the documentation says, but my code keeps running without arguments or even with arguments it doesn’t call the right function (it runs Language().make() in every case).
My argparse code:
lang = Language()
parser = argparse.ArgumentParser(description='e-cidadania language catalog generator.')
subparser = parser.add_subparsers()
parser_make = subparser.add_parser('make', help='Create all the language' \
' catalogs for translation,'\
' including JavaScript.')
parser_make.set_defaults(func=lang.make())
parser_compile = subparser.add_parser('compile', help='Compile all the language' \
' catalogs for use.')
parser_compile.set_defaults(func=lang.compile())
parser_clean = subparser.add_parser('clean', help='Delete all the language catalogs.' \
' After this you will'\
' have to rebuild the catalogs' \
' and translate them.')
parser_clean.set_defaults(func=lang.clean())
args = parser.parse_args()
The first line calls the only class in the file, called Language with three main methods, make, clean and compile and other private methods, _iterator and __init__.
Update The complete script is here: http://dpaste.com/hold/681317/
What I am missing from the documentation to run this?
That’s because you’re calling
makeyourself, here:In particullar, this part:
As a result, the
funcarg is set to the return value ofmake.Instead, you probably want to pass the method as argument, without calling it:
Update
Note that
argparsewill not call the methods for you. It will return them in thefuncattribute of theargsobject returned by the parser.So after you parse the args, you have to call it yourself:
Here
args.funcwill be one of the method objects (lang.make,lang.compileorlang.cleandepending on which command was specified as script argument). Applying the call operator()to it will execute it.