0

I am trying to run a python script in the command-line and would like to parse multiple analyses command with different optional parameters e.g.:

import argparse

parser = argparse.ArgumentParser()


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

# Analysis A
analysis_a_parser = subparsers.add_parser('analysis_a', help='description)
analysis_a_parser.add_argument('-flag1', action='store_true', default=False,
                                help='flag1 description')
analysis_a_parser.add_argument('-flag2', action='store_true', default=False,
                                help='flag2 description')
analysis_a_parser.add_argument('-flag3', action='store_true', default=False,
                                help='flag3 description')

# Analysis B
analysis_b_parser = subparsers.add_parser('analysis-b', help='description')
analysis_b_parser.add_argument('--Flag1', action='store_true', default=False,
                                help='flag1 description')
analysis_b_parser.add_argument('-Flag2', action='store_true', default=False,
                                help='flag2 description')


args = parser.parse_args()

After running the program on the command-line

$ python script.py analysis-a -flag1 analysis-b -flag2

it throws an error saying unrecognized arguments: analysis_b

Please could you explain how I can pass multiple commands and optional parameters.

  • The `subparsers` mechanism only allows one command. Once parsing has been passed to `analysis_a_parser` the main `parser` doesn't do any more parsing. – hpaulj Oct 22 '20 at 16:06
  • @hpaulj Thanks for you reply. Is there a way to get around the single command constraint of subparsers mechanism? –  Oct 22 '20 at 17:48
  • Sure, do your own parsing of `sys.argv` :( – hpaulj Oct 22 '20 at 18:38
  • @hpaulj Really?! I was hoping you would give me a nifty shortcut and help me avoid the labour of sys.argv parsing lol –  Oct 22 '20 at 20:06
  • i'm getting tired of hold `argparse` hands! People have used nested subparsers. `analysis_a_parser.add_subparsers` etc, but that gets messy pretty quick. – hpaulj Oct 22 '20 at 20:09
  • https://stackoverflow.com/questions/63361458/python-argparse-creates-incorrect-usage-string-when-using-nested-sub-parsers, https://stackoverflow.com/questions/64042616/python-argparse-with-subparsers-and-optional-positional-arguments, https://stackoverflow.com/questions/62250816/argparse-optional-arguments-with-multilevel-parser-subparser – hpaulj Oct 22 '20 at 20:16
  • @hpaulj Thanks for your help! Haha yeah these nested subparsers look like rabbit holes –  Oct 22 '20 at 20:45

0 Answers0