Search code examples
pythonpython-2.7getopt

handling getopt dynamically through different python script


I am using getopt to handle optional arguments in all my scripts. I have lots of scripts and i have to manage getopt in all the scripts separately because all scripts have different options.

My Question is is there any dynamic way to handle these options through single class by defining all options and just update those by objects ?

Currently i am using getopt like this:

import getopt 
if __name__=="__main__":
     if len(sys.argv) < 2:
         usage()
     else:
         try:
             options, remainder = getopt.getopt(sys.argv[2:], 's:n:i:a:c:t:p:', ['s1=','n1=','iteration=','api_v=', 'c='.....,])

         except getopt.GetoptError:
             print "\nError: Provided options are not correct!\n"
             usage()

        for opt, arg in options:
            if opt in ('-s', '--s1'):
                s1 = arg
            if opt in ('-n', '--n1'):
                try:
                    n1= int(arg)
                except ValueError:
                    print("Error : n1 not an integer!")
                    exit()
            elif opt in ('-i', '--iteration'):
                try:
                     timeout = int(arg)
                except ValueError:
                    print("Error : iteration not an integer!")
                    exit()

            elif opt in ('-a', '--abc'):
                abc = arg
                .....
                ....
            #and list goes on.

This i have in almost all my scripts with different options. Is there any cleaner way to achieve the same thing?


Solution

  • You may find the argparse module easier to use and read. You could create an ArgumentParser factory function in a separate module and just call that from all your scripts to return a parser with the correct options