Raheel
Raheel

Reputation: 9024

Command line arguments for functions in python

I have a python file which holds multiple functions. Each function will have its own parameters.

The first argument is the function to run. But I am unable to find how can i define arguments for my functions so that it will appear in argsparse help and also can validate.

import argparse

parser = argparse.ArgumentParser(description='Index related commands')
parser.add_argument('command', type=str)
arguments = parser.parse_args()

es = Es('myproject_elasticsearch')


def create(name):
    """

    :param name: Name of index
    :return: None
    """
    mapping = index_factory(name).get_mapping()
    es.create_index(name, mapping)


def index_factory(name):
    try:
        if name == 'catalog':
            index = Catalog()
            return index
        else:
            raise ValueError('Cannot find mapping for %s' % name)
    except ValueError as e:
        print (e)
        traceback.print_exc()
        exit(1)

Here the first postional argument will be the name of the command, in this case create.

What i want is the user can pass additional arguments which will be different on different functions.

example: $ python app.py create --catalog so this catalog will come as a argument to create function and can be viewed in the help also

Thanks

Upvotes: 0

Views: 46

Answers (1)

Thomas
Thomas

Reputation: 1066

Try OptionParser:

from optparse import OptionParser

def create(name):
    ...

def index_factory(name):
    ...


if __name__ == "__main__":

    usage = "usage: %prog [options] arg1"
    parser = OptionParser(usage=usage)

    parser.add_option("-i", "--index", dest="index",
                          help="the index to create")
    parser.add_option("-c", "--catalog", dest="catalog",
                          help="catalog name", default="my_catalog")

    (options, args) = parser.parse_args()

    if args[0] == 'create':
        create(options.index)
    elif args[0] == 'index_factory':
        index_factory(options.index)

Add as many options as you want. You can then call it like this

python app.py create -i my_index

or use help to see your options

python app.py -h

Upvotes: 1

Related Questions