Dealing with Command Line Options in Python
December 2nd, 2008 by Phil Hughes in
The one task remaining was to give it some options. That is, to pass it some criteria that would modify the report. Specifically, I wanted a start and end date and the ability to change the sort order from the default which was transaction date.
Before just jumping into the brute force way of dealing with the command line I decided to see if there was anything interesting in the Python libraries that might turn this into something a bit more pleasant. Well, I found good news in the form of the optparse module. From O'Reilly's Python in a Nutshell, I found the following description:
The optparse module offers rich, powerful ways to parse the command-line options that the user passed upon starting your programs.
Sounds good. My next check was on python.org with equally positive information. So, I decided to give it a try. Here is the short story (followed by a bit of code).
- First you instantiate the class OptionParser.
- For each option you want to use, you use the add_option method where you can specify the options (both short and long ones are supported) and tell optparse what to do.
- Once you are all set up, you use the parse_args method to do all the dirtywork. You then can just check for the existence of the options by checking for an attribute.
opts = OptionParser()
opts.add_option("--start", "-s", help="in format yyyy-mm-dd")
opts.add_option("--end", "-e", help="in format yyyy-mm-dd")
opts.add_option("--order", "-o", type="choice", choices=["tdate", "cname_id",
"account_id", "project_id", "id"], help="tdate|cname_id|account_id|project_id|id")
options, arguments = opts.parse_args()
if options.start:
...
if options.order:
...
That should be enough code. Each of the opts.add_option( lines adds an option to the list. For example, the first one says that it matches either --start or -s. The implied action is to store the argument associated with it. The help argument is used to specify a help message that is printed out either in case of an error calling the command or if the command is invoked with the -h option.
The third opts.add_option( line is a bit different. It defines the type of option as a choice and then includes a list of valid values. Entering anything other than one of these values results in an error message including the usage display.
The call to opts.parse_args() does the dirtywork for you. For example, if I had invoked the program with -s 2008-11-11 then options.start would be set to 2008-11-11.
All in all, I found optparse easy to understand and enjoyed separating all the error checking from using the arguments. There are lots more things it can do for you but this should get you started. It is now in my list of "Python tricks".
__________________________
Phil Hughes
Special Magazine Offer -- Free Gift with Subscription
Receive a free digital copy of Linux Journal's System Administration Special Edition as well as instant online access to current and past issues. CLICK HERE for offer
Linux Journal: delivering readers the advice and inspiration they need to get the most out of their Linux systems since 1994.
Subscribe now!
The Latest
Newsletter
Tech Tip Videos
- Jul-01-09
- Jun-29-09
Recently Popular
From the Magazine
July 2009, #183
News Flash: Linux Kernel 3.0 to include an on-the-go Expresso machine interface! Ok, maybe not, but Linux is definitely going mobile, from phones to e-readers. Find out more inside about Android, the Kindle 2, the Western Digital MyBook II, The Bug, and Indamixx (a portable recording studio). And if you've gone mobile and you been wanting more Emacs in your life then check out Conkeror.
To compliment the mobile we've got the stationary: parsing command line options with getopt, checking your Ruby code with metric_fu, and building a secure Squid proxy. How is this stationary you ask? What can we say? It's not. We just wanted to see if anybody actually read this part of the page :) .
All this and more, and all you have to do is get your hot sweaty hands on the latest copy of Linux Journal.
Delicious
Digg
StumbleUpon
Reddit
Facebook








Problem with program
On April 5th, 2009 Mike Tipton (not verified) says:
I am really new to Python. Basically I am trying to find examples of Python code, find out what it does and how it works, and why it works.
When I copied in the program, it is failing at the line
opts = OptionParser()
which is the first line of the program.
I have no idea why this is. Everyone (on the posts) says it works for them.
If this is a function call, I don't have a clue as to where it is SUPPOSED to be found. This is my main gripe with python. I download little programs and 90% of them never work. There is always something missing, and again, I don't know where to find it. When I downloaded and installed Python (2.6.1 I think) I "assumed" it was a complete package.
I was a COBOL programmer in a previous life, so I understand programming.
Where is a good web site that gives references to ALL of the commands just like the complete reference books on COBOL that I used to use? If I needed to know a command and how it works, I could just go to one place and I could find my answer.
Re: Problem with program
On May 13th, 2009 Nils R Grotnes (not verified) says:
Hi Mike.
The problem is this how-to wasn't aimed at you, a Python beginner, but rather those that know that such library modules must be imported before they can be used. Fortunately there's many good sources for getting started, in fact I bet you found the answer long before I posted this. Still, in case other beginners stumble upon this post, here's a good place to start looking for answers: http://www.python.org/doc/
Nils
great info
On March 31st, 2009 no steam (not verified) says:
Very interesting post, I was reading everything and I liked a lot, Keep it!
______
server counter strike
Good info
On March 31st, 2009 server counter strike (not verified) says:
Very interesting post, I was reading everything and I liked a lot, Keep it!
getopt
On March 2nd, 2009 magos (not verified) says:
Sorry for being lame in case i'm one, but could you now have used getopt()?
I'm just a python enthusiast!!
Thanks.
____
magos
Good one, thanks
On December 9th, 2008 Rec (not verified) says:
Well, is an easy one to make any app a notch easier to use.
Would be great to make a post out of everyone of the items in that Python tricks list you mention... ;)
Thanks again!
- Recetas EspaƱa
Rec
Just what I needed
On December 2nd, 2008 Anonymous (not verified) says:
I was just starting to look around for this solution last night, as a C and PHP programmer but Python n00b. Should help me out a great deal, thanks.
Post new comment