0

I would like to have a code that get the first argument as tool and after that expects different options depending on the tool

myapp.py [TOOL] [TOOLPARAMETERS]

python myapp.py tool0 -i 'path/to/my_image.jpg' -o 'path/to/my_output_path_folder/' -r 0.7 -m 13

python myapp.py tool1 -m 3 -r 'some_string_now' -m 13

As you can see in this case each tool could have it's own required arguments and in each case they could even expect different types

I have been messing around with add_subparsers with some success.

import argparse

parser = argparse.ArgumentParser(prog='myapp', usage='%(prog)s [tool] [options]')

parser.add_argument('-a', required=True, help='required globally argument for all tools')

subparsers = parser.add_subparsers(help='tool help')

#  subparser for tool0
parser_tool0 = subparsers.add_parser('tool0', help='tool 0 help')

# ADD tool0 ARGUMENTS
parser_tool0.add_argument('-i' , required=True, help='path to the input folder')
parser_tool0.add_argument('-o' , required=True, help='path to the output folder')
parser_tool0.add_argument('-r' , default=0.7,   type=float, help='some float')
parser_tool0.add_argument('-g' , default=10,    type=int, help='some integrer')
parser_tool0.add_argument('-d' , default=False, help='debug')


#  subparser for tool1
parser_tool0 = subparsers.add_parser('tool1', help='tool 0 help')

# ADD tool0 ARGUMENTS
parser_tool0.add_argument('-r' , help='r not required string')
parser_tool0.add_argument('-f' , required=True, help='f not required string')
parser_tool0.add_argument('-d' , default=0.7,   type=float, help='some float')
parser_tool0.add_argument('-i' , default=10,    type=int, help='some integrer')
parser_tool0.add_argument('-b' , default=False, help='boolean')
parser_tool0.add_argument('opts',
                        help='Modify config options using the command-line',
                        default=None, nargs=argparse.REMAINDER)

args = parser.parse_args()
print(args)

So I would like to know what should be the best practices for that case.

Thanks in advance

Jordi
  • 11
  • 2

1 Answers1

0

Per the docs and this so answer subparsers are the way to go.

user3474165
  • 171
  • 1
  • 3