Trying to run my script using argparser, where the program does not run, unless correct argument is in place, however it does not seem to work;
AttributeError: 'Namespace' object has no attribute 'func'
import sys import argparse from develop import Autogit as gt def main(): parser = argparse.ArgumentParser() subparsers = parser.add_subparsers() # Create argument command parser_update = subparsers.add_parser('--sync', help='Sync local and remote repos') parser_update.set_defaults(func=gt.run) # Adding arguments parser.add_argument('--sync', type=str, required=True) if len(sys.argv) <= 1: sys.argv.append('--help') options = parser.parse_args() options.func() # <--- Causes the error if __name__ == '__main__': main()
Also when the –sync arg is given it ask for another, then when I add one more argument. SYNC, then it returns attribute error.
Edit
Trying to make the program run the develop.Autogit.run
Working..
Had to also add args as argument in the run funciton i am calling.
Advertisement
Answer
I think what you are trying to accomplish is setting a default, typically this is done with ArgumentParser.set_defaults()
. You need to do this with the uninitialised function. See this example:
import sys import argparse def f(args): print("In func") print(args) def main(): parser = argparse.ArgumentParser() subparsers = parser.add_subparsers() # Create argument command parser_update = subparsers.add_parser("sync", help="Sync local and remote repos") parser_update.set_defaults(func=f) # <-- notice it's `f` not `f()` options = parser.parse_args() options.func(options) if __name__ == "__main__": main()
As an aside, you will have more problems with your snippet as you are defining the same parameter (--sync
) in multiple places. When using subparsers
it is customary to make these positional (no leading --
) so they act as subcommands.
Here is a typical command line that I would use with subcommands:
import sys import argparse def f(args): print("In func f") print(args) def g(args): print("In func g") print(args) def main(): parser = argparse.ArgumentParser() subparsers = parser.add_subparsers(dest="command") parser_update = subparsers.add_parser("sync", help="Sync local and remote repos") parser_update.set_defaults(func=f) parser_delete = subparsers.add_parser("delete", help="Delete sub-command") parser_delete.set_defaults(func=g) options = parser.parse_args() if options.command is not None: options.func(options) else: parser.print_help() parser.exit() if __name__ == "__main__": main()