Using optparse in python

Sometimes we have to create tools that takes input as argument with certain options. We can create such tool with optparse module of python.

Here is a small example of using this.


from optparse import OptionParser

parser = OptionParser(usage='usage: %prog [options] arguments')

parser.add_option('-a',help="setup/cleanup",action="store", dest="action")
parser.add_option('-m',help="email id",action="store", dest="email")
parser.add_option('-i',help="Input json props",action="store", dest="input")
(options, args) = parser.parse_args()

For help, type: ( This will display all the arguments that can be used with their format)

python -h

Usage: [options] arguments

-h, –help show this help message and exit
-a ACTION setup/cleanup
-m EMAIL email id
-i INPUT Input json props

save it in a programme and execute it as :

python -a setup -i file.json -m


Now we can access the above inputs and use them, using below variables inside the programme:





About Divyashree - The GNULINUX Guy

I am a Linux and Opensource enthusiast. I started working on Linux early in 2007 while I was doing my Masters in Computer Science and passed out in 2010. Currently working as a DevOps Developer in in Public/Private cloud domain. my @github : my @nagiosexchange : my @linkedin :☁-a9415615
This entry was posted in ARTICLES, DevOps, HOWTO, Programming, TIPS & T RICS and tagged , , . Bookmark the permalink.

Leave a Reply

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

You are commenting using your 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 )

Google+ photo

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

Connecting to %s