0

I have a python project with multiple scripts. The structure is organized as:

project-folder
   ...
   src
      scripts
         script1
         script2
   __main__.py

I want to execute the scripts at project-folder level, where you can invoke the script you wanna execute as python -script1 or python -script2. If you specify script1, then you are allowed to provide all relevant command-line arguments for script1, i.e. python -script1 -script1param1="..." -script1param2="...", etc. For script2 applies the same: python -script2 -script2param1="..." -script2param2="...".

I could define at script level script specific cmd options, like python -script1param1="..." -script1param2="..." or python -script2param1="..." -script2param2="...", and at project-folder level the option which script you want to run, either python -script1 or python -script2, but I couldn't combine both in one.

Any ideas on this?

Thanks in advance.

mbrb
  • 393
  • 1
  • 2
  • 12

1 Answers1

0

I figured out how to do it

(Thanks to Conditional command line arguments in Python using argparse and Select limited arguments from Parent Parser)

parser = argparse.ArgumentParser(
    description="Run one of the following scripts.\n"
                "- 1: python . script1 -script1param1='...' -script1param2='...'\n"
                "- 2: python . script2 -script2param1='...' -script2param2='...'",
    formatter_class=RawTextHelpFormatter
)

subparsers = parser.add_subparsers(
    dest='action',
    help="Adds script specific command line arguments.")

script1_parser = script1.get_parser()
script1_parser = subparsers.add_parser("script1",
                                     parents=[script1_parser],
                                     add_help=False,
                                     help="Runs script 1.")
script2_parser = script2.get_parser()
script2_parser = subparsers.add_parser("script2",
                                     parents=[script2_parser],
                                     add_help=False,
                                     help="Runs script 2.")

args = parser.parse_args()

if args.action == 'script1':
    script1.main(args)
elif args.action == 'script2':
    script2.main(args)

So the key elements here are actually:

  1. the subparsers where we can attach a 'branch' parser based on action value (script1 or 2); and
  2. the parents parameter of add_parser. In each script we define its args parser, get the parser by script.get_parser(), and pass it to add_parser in parents.
mbrb
  • 393
  • 1
  • 2
  • 12