0

My program boiler uses argparse for parsing command line options and subparser chain (in fact, I am going to add more subcommands). It should take the option -t both for the main option parser and for the subparser.

Example:

boiler -t URL chain

is equivalent to

boiler chain -t URL

The subcommand parser's option overrides the global option. For example:

boiler -t URL1 chain -t URL2

is equivalent to

boiler chain -t URL2

What is the most elegant way to code this with Python argparse?

The thing I am really going to do is describes in this answer: https://stackoverflow.com/a/53750697/856090 of the question Chaining in a command line several tranformations with options. Take note that the above described is not exactly what I need, but I need to parse a pipeline of subcommands as described there (some of these subcommands may take -t option and other options with possible global default).

Example of what I really need:

boiler -t URL1 pipe 'chain -t URL2 + chain'

Here the first chain of two chains separated by + uses URL2 and the second one uses URL1.

porton
  • 5,214
  • 11
  • 47
  • 95
  • You can define a `-t` for both main and subparser, but give them different `dest`. That way the default (or value) of the subparser `-t` won't step on the value for the main. – hpaulj Dec 13 '18 at 03:13
  • 1
    https://bugs.python.org/issue9351 - is the patch that gave priority to the subparser defaults. See also https://stackoverflow.com/questions/50543820/argparse-options-for-subparsers-override-main-if-both-share-parent and https://stackoverflow.com/questions/37933480/how-can-i-define-global-options-with-sub-parsers-in-python-argparse – hpaulj Dec 13 '18 at 07:39

0 Answers0