SecondGear
SecondGear

Reputation: 1113

python argparse : how to override all other parameters - like --help does in most programs?

We have a bunch of scripts that use a standard set of parameters. These are defined in a class that all scripts use. Each scripts can add additional parameters as needed.

I'm trying to add a new parameter that should act like --help in that if present, all other parameters are ignored. When the new parameter (--doc_string) is given, I want all other parameters to be ignored, I will print a specific string and exit. Is there a way to do this with argparse?

I've looked at using groups like this:

parser = argparse.ArgumentParser(prog='PROG')
group1 = parser.add_argument_group('docs', 'doc printing')
group1.add_argument('--doc_string', action = 'store_true', help='print the doc string and exit')
group2 = parser.add_argument_group('group2', 'group2 description')
group2.add_argument('--bar', required=True, help='bar help')
group2.add_argument('--blah',required=True, help='url used to test.')
parser.parse_args()

But when run with just --doc_string, I still get the message --bar is required. Exclusive groups isn't right either.

I've also looked at subclassing argparse.RawDescriptionHelpFormatter or argparse.RawTextHelpFormatter or argparse.ArgumentDefaultsHelpFormatter but can't get a handle on how to use those to accomplish what I'm trying to do.

Upvotes: 5

Views: 7027

Answers (1)

wim
wim

Reputation: 362557

Register your own action with the parser. Then you can do it the same way --help, --version etc do it, i.e. by specifying the action.

import argparse

class DocstringAction(argparse.Action):

    def __call__(self, parser, namespace, values, option_string=None):
        print('see ya later alligator')
        parser.exit()

parser = argparse.ArgumentParser(prog='PROG')
parser.register('action', 'docstring', DocstringAction)
group1 = parser.add_argument_group('docs', 'doc printing')
group1.add_argument('--doc_string', nargs=0, action='docstring', help='print the doc string and exit')
group2 = parser.add_argument_group('group2', 'group2 description')
group2.add_argument('--bar', required=True, help='bar help')
group2.add_argument('--blah',required=True, help='url used to test.')
parser.parse_args()

If you don't need any arguments for the docstring action, then you could (should) push the nargs=0 into DocstringAction.__init__ so that it's not necessary to specify that.

Upvotes: 7

Related Questions