Python Command Line Arguments: Calling a function

lesley2958 picture lesley2958 · Jun 5, 2015 · Viewed 14k times · Source

So I'm stuck on a project I'm working on that involves the command line in python.

So basically, here's what I'm trying to accomplish:

I have a set of functions in a class, say,

def do_option1(self, param1, param2) :
    #some python code here

def do_option2(self, param1): 
    #some python code here

def do_option3(self, param1, param2, param3):
    #some python code here

And so basically, when a user puts filename.py option2 param1 into the command line, I want it to call the function do_option2 and pass the parameter, param1, to it.

Similarly, when a user puts filename.py option3 param1 param2 param3, I want it to execute the do_option3 function with the given parameters.

I know there are 2 modules in python called argparse and optparse, but I've had difficulty understanding the two and i'm not sure if either of the two alone will accomplish what I need done.

Answer

chepner picture chepner · Jun 5, 2015

Using argparse subcommand parsers

p = argparse.ArgumentParser()
subparsers = p.add_subparsers()

option1_parser = subparsers.add_parser('option1')
# Add specific options for option1 here, but here's
# an example
option1_parser.add_argument('param1')
option1_parser.set_defaults(func=do_option1)

option2_parser = subparsers.add_parser('option2')
# Add specific options for option1 here
option2_parser.set_defaults(func=do_option2)

option3_parser = subparsers.add_parser('option3')
# Add specific options for option3 here
option3_parser.set_defaults(func=do_option3)

args = p.parse_args()
args.func(args)

Then each of your do_option functions would need to be rewritten slightly to take a single argument from which it can extract the values it needs. For example:

def do_option1(args):
    param1 = args.param1
    # And continue