Problem

How do I write a command help in Python?

Solution

In python there are two different ways to look for command-line switches, depending on the case:


1. Examine sys.argv directly. This is useful when you want to look for specific command-line switches from a Python module (as opposed to a stand-alone script).
2. Use the optparse module. Useful for stand-alone scripts where you know all the command-line switches that will be used ahead of time.


Here a brief example of both cases:


###############--Case 1--##################
 from sys       import argv

if len(sys.argv) < 1:
   printUsage(); 

 for i in range(0, len(argv) - 1):
    if argv[i] == '-option' or argv[i] == '-o':
       #Found it!  OK to set now.
       OPTION_ARG = argv[i + 1]
    if argv[i] == '-help' or argv[i] == '-h':
       printUsage()

###############--Case 2--##################

Take a look to the example of this page: http://www.python.org/doc/current/lib/module-optparse.html