Home > Python > Option parser in Python

Option parser in Python

I have just started playing around with Python like a few weeks back and having lots of fun scripting in it. Today at work got to know of a very nice feature with Python which lets you easily configure the options taken from command line, which is called option parser.

Firstly, you need to include the library with ‘import’:

from optparse import OptionParser

Now you can use it like this:

usage = "usage: %prog -H hostname -p port -d diskpath -t threshold"
parser = OptionParser(usage=usage, version="%prog 1.0")
parser.add_option("-H", "--host", action="store", type="string", dest="hostname",
help="input host name for database server")
parser.add_option("-d", "--disk", action="store",
type="string", dest="diskpath", help="input disk path")
parser.add_option("-p", "--port", action="store", type="string",
dest="dbport", help="input port for database server")
parser.add_option("-t", "--thresh", action="store", type="int",
dest="thresh", help="input threshold for disk size ")

Where every add_option means adding a new argument on command line to check for and the best thing is you just put in the help section with the add_option function call and it automagically builds the full help section for the program to be use with “-h”, so that means you cant have an option with “-h” as that clashes with the default help option for option parser, and that was the reason I had to go with “-H” for hostname 🙂

In order to get the values into variables just simply use:

(options, args) = parser.parse_args()
if options.hostname:
if options.diskpath:
if options.dbport:
if options.thresh:

Now when you run the program with “-h” option you get the following:

shoaib@shoaib-desktop:~/Desktop/Scripts$ ./mgmnt -h
Usage: mgmnt -H hostname -p port -d diskpath -t threshold
--version             show program's version number and exit
-h, --help            show this help message and exit
input host name for database server
input disk path
-p DBPORT, --port=DBPORT
input port for database server
-t THRESH, --thresh=THRESH
input threshold for disk size

Shoaib Mir

Categories: Python Tags: ,
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: