6

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!

1
  • Look at the full subparsers set_defaults example in the docs. Commented Feb 28, 2018 at 21:32

1 Answer 1

16

Because you need to invoke the function manually by args.func(args):

import argparse 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() args.func(args) def command1(args): print("command1: %s" % args.name) def command2(args): print("comamnd2: %s" % args.frequency) if __name__ == '__main__': main() 
Sign up to request clarification or add additional context in comments.

3 Comments

This throws the error AttributeError: 'Namespace' object has no attribute 'func' at the line args.func(args) if the program is run without any arguments.
@FilipS. right. This is just the minimal change to make the OP's code to work. Whoever use this code should add relevant sanitation checks.
You can add a required=True to subparsers = parser.add_subparsers() to have argparse run the check for you.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.