Python getopt optional command line parameters
Question: I finished writing a script in python, and now stuck in the interface, which
requires getting few options from user but not sure what is the best way to
get optional arguments.. The code for that is as below...

    
    
    def getOptions(argv):
           try:
                opts,args = getopt.getopt(argv, "hi:c:d:m", ["ifile=", "add=", "delete"])
            except getopt.GetoptError:
                printUsage() 
                sys.exit(2)
            for opt, arg in opts:
                if opt in ("-h", "--help"):
                    print ("test -m <make> [src] [dst]\n")
                    print ("test -i <install>[filename] \n")
                    .....
                    sys.exit()
                if opt in ( "-m", "--make"):
                    make(arg)
                    sys.exit()
                if opt in ("-i","--install"):
                    install(arg)
                    sys.exit()
                ... # few more options
                else:
                    assert False, "unhandled option"
    

My question is that how can i leave out the argument (like use a default
optional path for arg) and if that is not provided, get from user ?? Currently
i've to provide ./test -i how can i leave out file name and call like ./test
-i  
Secondly, how can i combine two options (without any argument for example,
./test -i -m


Answer: From: <https://docs.python.org/2/library/getopt.html> Getopts does not support
optional arguments.

Can you trying writing your code using argparse? Following is an example:

    
    
    import argparse
    parser = argparse.ArgumentParser(description='python cli')
    parser.add_argument("-m", "--make", help="execute make", required=True)
    parser.add_argument("-i", "--install", help="execute install", required=True)
    
    # parse input arguments
    args = parser.parse_args()
    
    makeVal = args.make
    shouldInstall = args.install
    
    if makeVal :
        make(makeVal)
    ...
    

Reference: <https://docs.python.org/2.7/library/argparse.html>

