Hello I am starting with argparse. My goal is to build a CLI with main commands that accept arguments and redirect to the corresponding commands functions. Here is what I did so far:
def main(): parser = argparse.ArgumentParser() subparsers = parser.add_subparsers() command1_parser = subparsers.add_parser('command1') command1_parser.set_defaults(func=command1) command1_parser.add_argument('--name', dest='name') command2_parser = subparsers.add_parser('command2') command2_parser.set_defaults(func=command2) command2_parser.add_argument('--frequency', dest='frequency') args = parser.parse_args() def command1(): # do something with args.name def command2(): # do something with args.frequency if __name__ == '__main__': main() When I do:
entrypoint command1 --name Hello Or:
entrypoint command2 --frequency 10 It fails to catch the corresponding args. What I am doing wrong? Thanks!
subparsersset_defaultsexample in the docs.