Tuesday, November 13, 2012

Option Parsing in Python

Another helpful Python module is "optparse" which provides a command line option parser.   It lets you define your command line options and then parses the command line for you.   It supports both dash and double-dash formats, logicals, defaults, and even sub options.

I used it for the script that I assembled when I was playing with the RPi GPIO functionality which accepted as options the message to be displayed, the color for the RGB LED, and the standard "interval" to use for signaling.   The definition code is shown below:

    # Get command line options    parser = OptionParser()    parser.add_option("-m", "--message", dest="message", default="SOS",
                  help="Message to blink out in morse code")
    parser.add_option("-r", "--red", dest="red", default=255,
                  help="Red component for blink")
    parser.add_option("-g", "--green", dest="green",  default=0,
                  help="Green component for blink")
    parser.add_option("-b", "--blue", dest="blue", default=0,
                  help="Blue component for blink")
    parser.add_option("-i", "--interval", dest="interval", default=200,
                  help="Length of standard interval in milliseconds")
    (options, args) = parser.parse_args()

Options can be retrieved as shown here:

    # Execute!
    _execute(_compile(options.message), int(options.red), 

        int(options.green), int(options.blue))

I did not use this in the GPIO script but you can easily dump the contents of your options as shown here:

    logger.debug("Initiating startup with the following options:")
    for key, val in vars(options).iteritems():
        logger.debug("    " + key + " = '" + str(val) + "'")

No comments:

Post a Comment