I want to implement commands with argparse and share common arguments between them. At the same time these commands have some unique arguments that should only be available to the specific parser.
My current code looks like this:
parser = argparse.ArgumentParser(description='test')
parser.add_argument('command', help='Subcommand to run')
parser.add_argument("--opta",
help="usa a",
action="store_true")
parser.add_argument("--optb",
help="Use b",
action="store_true")
subparser = parser.add_subparsers(help="")
parser_1 = subparser.add_parser("cmd1",
help="do 1",
parents=[parser], add_help=False)
parser_1.add_argument("--yes", "-y",
help="just do it",
action="store_true")
parser_1.add_argument("--dry-run", "-s",
help="Simulate actions",
action="store_true")
parser_2 = subparser.add_parser("cmd2",
help="do 2",
parents=[parser], add_help=False)
parser_2.add_argument('--choice', choices=['c', ''], default='',
help="choose something")
print(sys.argv)
args = parser.parse_known_args()
print(args)
When executing this code I get an error message by argparse claiming the input to be unknown.
./test.py cmd2 --opta --choice c
['./test.py', 'cmd2', '--opta', '--choice', 'c']
usage: test.py [-h] [--opta] [--optb] command {cmd1,cmd2} ...
test.py: error: invalid choice: 'c' (choose from 'cmd1', 'cmd2')
cmd1 however seems to work.
./test.py cmd1 --opta --yes
['./test.py', 'cmd1', '--opta', '--yes']
(Namespace(command='cmd1', opta=True, optb=False), ['--yes'])
What am I overlooking? Is there a more elegant way of using argparse for this?