0

I have a program which is called like this:

program.py add|remove|show 

The problem here is that depending on the add/remove/show command it takes a variable number of arguments, just like this:

program.py add "a string" "another string"
program.py remove "a string"
program.py show

So, 'add' command would take 2 string arguments, while 'remove' command would take 1 only argument and 'show' command wouldn't take any argument. I know how to make a basic argument parser using the module argparse, but I don't have much experience with it, so I started from this:

import argparse
parser = argparse.ArgumentParser()
parser.add_argument("command", choices=["add", "remove", "show"])

But I don't know how to continue and how to implement this functionality depending on the command. Thanks in advance.

1 Answer 1

2

You're looking for argparse's subparsers...

parser = argparse.ArgumentParser(prog='PROG')
subparsers = parser.add_subparsers(help='sub-command help')

# create the parser for the "add" command
parser_add = subparsers.add_parser('add', help='add help')
# [example] add an argument to a specific subparser
parser_add.add_argument('bar', type=int, help='bar help')

# create the parser for the "remove" command
parser_remove = subparsers.add_parser('remove', help='remove help')

# create the parser for the "show" command
parser_show = subparsers.add_parser('show', help='show help')

This example code is stolen with very little modification from the language reference documentation.

Sign up to request clarification or add additional context in comments.

2 Comments

How do I check which option has been chosen and get the correspondent variables?
@xBlackout -- the documentation I linked gives advice on that too ... Search the page for a sentence that starts with "One particularly effective way of handling sub-commands". The tl;dr; is that you can use set_defaults to attach a function to the namespace based on which subparser was selected. Then you just call that function to execute the actions associated with the selected subparser.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.