optparse

Steven Bethard steven.bethard at gmail.com
Wed Sep 27 20:00:27 EDT 2006


rick wrote:
> Consider the following piece of code:
> 
> parser = optparse.OptionParser(usage="usage: %prog <input filename> 
> <output filename> [options]", add_help_option=False)
> parser.add_option("-d", type="string", action="store", dest="DELIM", 
> default="|", help="single character delimiter in quotes (default: |)")
> (options, args) = parser.parse_args()
> 
> 
> Is there any way I can add help for the arguments (<input filename> and 
> <output filename>) in the same table that optparse generates above the 
> options section. Ideally, I would like the output as:
> 
> ======================================================
> usage: DelimTOFixedWidth.py <input filename> <output filename> [options]
> 
> required:
>  input filename     name of the delimited input file
>  output filename   name of fixed-width output file
> 
> options:
>  -d DELIM  single character delimiter in quotes (default: |)
> ======================================================
> 
> Is that possible using optparse?

Not easily, but that's exactly what the argparse_ module is for::

     >>> import argparse
     >>> parser = argparse.ArgumentParser(add_help=False)
     >>> parser.add_argument('-d', dest='DELIM', default='|',
     ...     help='character delimiter in quotes (default: %(default)s)')
     >>> parser.add_argument('input_filename',
     ...     help='name of the delimited input file')
     >>> parser.add_argument('output_filename',
     ...     help='name of fixed-width output file')
     >>> parser.print_help()
     usage: tasks.py [-d DELIM] input_filename output_filename

     positional arguments:
       input_filename   name of the delimited input file
       output_filename  name of fixed-width output file

     optional arguments:
       -d DELIM         character delimiter in quotes (default: |)

Note that argparse_ also figures out the correct usage message for you.

.. _argparse: http://argparse.python-hosting.com/

STeVe



More information about the Python-list mailing list