Dealing with Command Line Options in Python
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
Today’s modular x86 servers are compute-centric, designed as a least common denominator to support a wide range of IT workloads. Those generic, virtualized IT workloads have much different resource optimization requirements than hyperscale and cloud applications. They have resulted in a “one size fits all” enterprise IT architecture that is not optimized for a specific set of IT workloads, and especially not emerging hyperscale workloads, such as web applications, big data, and object storage. In this report, you will learn how shifting the focus from traditional compute-centric IT architectures to an innovative disaggregated fabric-based architecture can optimize and scale your data center.
Sponsored by AMD
Built-in forensics, incident response, and security with Red Hat Enterprise Linux 6
Every security policy provides guidance and requirements for ensuring adequate protection of information and data, as well as high-level technical and administrative security requirements for a system in a given environment. Traditionally, providing security for a system focuses on the confidentiality of the information on it. However, protecting the data integrity and system and data availability is just as important. For example, when processing United States intelligence information, there are three attributes that require protection: confidentiality, integrity, and availability.
Learn more about catching the bad guy in this free white paper.
Sponsored by DLT Solutions
| Using Salt Stack and Vagrant for Drupal Development | May 20, 2013 |
| Making Linux and Android Get Along (It's Not as Hard as It Sounds) | May 16, 2013 |
| Drupal Is a Framework: Why Everyone Needs to Understand This | May 15, 2013 |
| Home, My Backup Data Center | May 13, 2013 |
| Non-Linux FOSS: Seashore | May 10, 2013 |
| Trying to Tame the Tablet | May 08, 2013 |
- Making Linux and Android Get Along (It's Not as Hard as It Sounds)
- Using Salt Stack and Vagrant for Drupal Development
- New Products
- Validate an E-Mail Address with PHP, the Right Way
- Drupal Is a Framework: Why Everyone Needs to Understand This
- A Topic for Discussion - Open Source Feature-Richness?
- Home, My Backup Data Center
- New Products
- RSS Feeds
- Tech Tip: Really Simple HTTP Server with Python
- Epistle
48 min 13 sec ago - Automatically updating Guest Additions
1 hour 56 min ago - I like your topic on android
2 hours 43 min ago - Reply to comment | Linux Journal
3 hours 4 min ago - This is the easiest tutorial
9 hours 18 min ago - Ahh, the Koolaid.
14 hours 57 min ago - git-annex assistant
20 hours 57 min ago - direct cable connection
21 hours 19 min ago - Agreed on AirDroid. With my
21 hours 29 min ago - I just learned this
21 hours 34 min ago
Enter to Win an Adafruit Prototyping Pi Plate Kit for Raspberry Pi

It's Raspberry Pi month at Linux Journal. Each week in May, Adafruit will be giving away a Pi-related prize to a lucky, randomly drawn LJ reader. Winners will be announced weekly.
Fill out the fields below to enter to win this week's prize-- a Prototyping Pi Plate Kit for Raspberry Pi.
Congratulations to our winners so far:
- 5-8-13, Pi Starter Pack: Jack Davis
- 5-15-13, Pi Model B 512MB RAM: Patrick Dunn
- Next winner announced on 5-21-13!
Free Webinar: Linux Backup and Recovery
Most companies incorporate backup procedures for critical data, which can be restored quickly if a loss occurs. However, fewer companies are prepared for catastrophic system failures, in which they lose all data, the entire operating system, applications, settings, patches and more, reducing their system(s) to “bare metal.” After all, before data can be restored to a system, there must be a system to restore it to.
In this one hour webinar, learn how to enhance your existing backup strategies for better disaster recovery preparedness using Storix System Backup Administrator (SBAdmin), a highly flexible bare-metal recovery solution for UNIX and Linux systems.



Comments
Specifying a file name containing a space
How would one specify a file name when that file name contains a space. Many of the primers on Python command line processing provide such simple examples and do not deal with this very real world case. For example, I want to supply something like this.
PrepareReport.py -f "My Output File.txt"
or would it be:
PrepareReport.py -f="My Output File.txt"
adding the equals sign after the "-f" option?
Arguments with spaces
Assuming you have something like this:
from optparse import OptionParser opts = OptionParser() opts.add_option("--file", "-f", type="string", help="a file") options, arguments = opts.parse_args() if options.file: print options.filethe following work:
PrepareReport.py -f "My Output File.txt" PrepareReport.py -f"My Output File.txt" PrepareReport.py "-fMy Output File.txt" PrepareReport.py --file "My Output File.txt" PrepareReport.py --file="My Output File.txt" PrepareReport.py "--file=My Output File.txt"Mitch Frazier is an Associate Editor for Linux Journal.
Problem with program
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
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
Good info
Very interesting post, I was reading everything and I liked a lot, Keep it!
getopt
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
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
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.