I wanted to create an interface with argparse
for my script with subcommands; so, if my script is script.py
, I want to call it like python script.py command --foo bar
, where command
is one of the N possible custom commands.
The problem is, I already tried looking for a solution here on StackOverflow, but it seems like everything I tried is useless.
What I have currently is this:
parser = argparse.ArgumentParser()
parser.add_argument("-x", required=True)
parser.add_argument("-y", required=True)
parser.add_argument("-f", "--files", nargs="+", required=True)
# subparsers for commands
subparsers = parser.add_subparsers(title="Commands", dest="command")
subparsers.required = True
summary_parser = subparsers.add_parser("summary", help="help of summary command")
- If I try to run it with:
args = parser.parse_args("-x 1 -y 2 -f a/path another/path".split())
I got this error, as it should be: script.py: error: the following arguments are required: command
.
- If, however, I run this command:
args = parser.parse_args("summary -x 1 -y 2 -f a/path another/path".split())
I got this error, that I shouldn't have: script.py: error: the following arguments are required: -x, -y, -f/--files
.
- If I put the command at the end, changing also the order of arguments because of
-f
, it works.
args = parser.parse_args("-x 1 -f a/path another/path -y 2 summary".split())
If I add the
parents
keyword in subparser, so substitute thesummary_parser
line withsummary_parser = subparsers.add_parser("summary", help=HELP_CMD_SUMMARY, parents=[parser], add_help=False)
, then I got:script.py summary: error: the following arguments are required: command
whensummary
is in front of every other argument;script.py summary: error: the following arguments are required: -x, -y, -f/--files, command
whensummary
is at the end of the args.
My question is, how I have to setup the parsers to have the behaviour script.py <command> <args>
? Every command shares the same args, because they are needed to create certain objects, but at the same time every command can needs other arguments too.