outputting a command to the terminal?

Steven Bethard steven.bethard at gmail.com
Mon Aug 14 13:19:44 EDT 2006


Yu-Xi Lim wrote:
> Steven Bethard wrote:
>> import argparse # http://argparse.python-hosting.com/
>> import subprocess
>> import sys
> 
> Why not the standard lib's optparse?

The page referenced above gives a variety of reasons, but the two most 
important things in this example are: argparse supports parsing of both 
positional and optional arguments, and argparse generates better usage 
messages.

Since argparse supports positional arguments, I can write something like::

     parser.add_argument('packages', ..., nargs='+', ...)

and then the arparse module will enforce that at least one positional 
argument was given. With optparse, you'd do something like:

     options, args = parser.parse_args()
     if not args:
         parser.error('wrong number of arguments')

Basically, with optparse, anything that involves positional arguments 
has to be handled by the user.

It's also worth pointing out the better usage messages. Notice that the 
output looked like::

     $ scriptname.py -h
     usage: scriptname.py [-h] [--save SAVE] package [package ...]

     positional arguments:
       package      one of the packages to install

     optional arguments:
       -h, --help   show this help message and exit
       --save SAVE  a file to save the package names to

With the optparse, you'd get something like::

     $ scriptname.py -h
     usage: scriptname.py [OPTIONS]

     options:
       -h, --help   show this help message and exit
       --save SAVE  a file to save the package names to

The argparse module knows how to create a meaningful usage message 
instead of just "%prog [OPTIONS]", and the argparse module knows about 
positional arguments, so you can have help messages for them too.

Ok, enough propaganda for now. ;-)

STeVe



More information about the Python-list mailing list