Python OptionParser

I love when code makes life easier. However, if you don’t know what the code does… life isn’t so easy now. That’s why we have man pages!

In honor of those “man” pages…

Except building a man page for a script and handling the “-h” argument from a command prompt can be tedious.

Python has a really cool library called optparse, that includes the ability to make a “help” output for a script along with argument handling. You know how nice that is to have a library take care of the whole argument handling? Very nice! I would hate to use regular expressions to try and parse a list of command line inputs.

If my blog posts about the language haven’t made this obvious already, I really love Python. It does have faults because it is not a type-safe language and in some circumstances that can be an issue. I’ll go into detail at a later time. Ideally, it is best to have both type-safe and dynamic type languages in your repertoire of tools.

Anyways, back to Optparse. It’s basically self-explanatory.

Import OptionParser.

from optparse import OptionParser

Next, setup an OptionParser object.

parser = OptionParser()

Give it some flags or parameter options. You do not have to create a -h or help option, this will be created for you automatically. Below is a template for creating an option.

parser.add_option("-<OPTION LETTER>", "--<OPTION NAME>", dest="<VARIABLE NAME TO STORE OPTION CONTENT>", default=<DEFAULT VALUE>, help="<HELP TEXT>")

Each option creates a possible input parameter that user’s can specify. If you do not want the user to have to input a value, maybe a flag is more your style.

A flag is a true or false notification that does not require additional user input. If a flag is present do something, if not do something else. To create a flag, set the default option to true or false and add “action=”store_true” or add “action=”store_false” in order to simulate a flag option. When you want the flag to turn a statement true set “action=”store_true” and “default=False” and the exact opposite for a flag to turn something false. 

To help clarify things, I wrote up a fun example below.


The below was coded for Python 2.7 and saved to a file called

from optparse import OptionParser
import os, time

def somethingCool(dazzling):
    print "Something Cool"
    if dazzling:
        print "\n~*~*~*~*~*~*~"+dazzling+"~*~*~*~*~*~*~"

def somethingStupid(dazzling):
    print "Something Stupid..."
    if dazzling:
        print "\n--------------"+dazzling+"--------------"

def main():
    parser = OptionParser() #Help menu options
    parser.add_option("-c", "--cool", action="store_true", dest="cool", default=False, help="Do something cool!")
    parser.add_option("-s", "--stupid", action="store_true", dest="stupid", default=False, help="Do something stupid...")
    parser.add_option("-d", "--dazzling", dest="dazzling", default=None, help="Add this dazzling text to the cool or stupid thing.")
    (options, args) = parser.parse_args()
    elif options.stupid:
        print "Lame, you selected nothing..."

if __name__ == "__main__":


OptionParser will automatically create a help option (-h) for you. Here is what the help screen looks like for my code example:

Screen Shot 2014-01-21 at 3.52.37 PM

Basically, if I call the script with the -c flag, something cool will happen.

python -c

If I call the script with the -s flag, something stupid will happen.

python -s

Screen Shot 2014-01-21 at 3.52.55 PM

If I call the script with the -d <TEXT> and a flag something will happen with text.

python -c -d "My Blog at"

Screen Shot 2014-01-21 at 3.54.36 PM

If I don’t provide a -s or a -c flag, the code insults me… A flag isn’t required but nothing else will happen if one isn’t given.

Screen Shot 2014-01-21 at 4.07.48 PM

Check out for more details. Have fun!

Leave a Reply

Your email address will not be published. Required fields are marked *


Time limit is exhausted. Please reload the CAPTCHA.

This site uses Akismet to reduce spam. Learn how your comment data is processed.