I have a CLI that I'm trying to improve. What I would like to do is have an optional argument with 3 choices, and depending on your choice you are required to enter certain arguments to that choice.
For example:
--create dog DOG_NAME DOG_BREED
OR
--create cat CAT_NAME
OR
--create fish FISH_BREED FISH_TANK
etc.
So this would look something along the lines of:
parser.add_argument("--create", help="Create an animal", choices=["dog", "cat", "fish"])
But how do I have different required arguments for each of the choices? Do I have to use subparser?
EDIT: Went with a slightly different schema and got it to work.
parser = argparse.ArgumentParser()
subparsers = parser.add_subparsers(title="actions", dest="subcmd")
subp_create = subparsers.add_parser("create", description="Create a Dog, Cat, or Fish")
subp_delete = subparsers.add_parser("delete", description="Delete a Dog, Cat, or Fish")
subp_create.add_argument("--dog", help="Create a Dog", nargs=2, metavar=(DOG_NAME, DOG_BREED))
#etc.
args = parser.parse_args()
handle_args(args)
def handle_args(args):
if args.subcmd == "create":
if args.dog:
dog_name = args.dog[0]
dog_breed = args.dog[1]
#Do whatever you need