Jzl5325
Jzl5325

Reputation: 3974

argparse call a function after parsing other options

Currently, I am using argparse to parse arguments and store flags as boolean options. I then check to see which flag is set to true and execute that function. Argparse parses an input file, which is opened and passed to the called function as an argument.

So:

parser.add_argument('input_data', action='store', help='some help')
parser.add_argument('outputname', action='store',default=None, help='some help')
parser.add_argument('--flag','-f', action='store_true', dest='flag', default=False, help='help!')

I have to open the input_data to read some information from it before the flag function is called. This is currently implemented as:

if args.flag == True:
    array_out = flag(array_read_from_input)
    if args.outputname == None:
        name = 'Flag.tif'

It is possible to subclass argparse to have the action keyword call a function.

Is it possible to parse the input_data option, perform some processing, and then call the flag function without having nested if loops for each argument, eg., by subclassing argparse's action parameter?

Upvotes: 5

Views: 2974

Answers (1)

danodonovan
danodonovan

Reputation: 20353

Is it possible to parse the input_data option, perform some processing, and then call the flag function without having nested if loops for each argument, eg., by subclassing argparse's action parameter?

As per your question;

class FooAction(argparse.Action):
    def __call__(self, parser, namespace, values, option_string=None):
        << some processing of values >>
        array_out = flag(values)
        setattr(namespace, self.dest, array_out)

parser = argparse.ArgumentParser()
parser.add_argument('input_data', action=FooAction, help='some help')

Upvotes: 0

Related Questions