optparse: best way

Ben Finney ben+python at benfinney.id.au
Tue Jun 8 06:15:35 EDT 2010


hiral <hiralsmaillist at gmail.com> writes:

> Command syntax:
> myscript -o[exension] other_arguments
>     where; extension can be 'exe', 'txt', 'pdf', 'ppt' etc.

It's more generally applicable to refer to that as a “suffix” for the
filename, and specify the full suffix including the full-stop (‘.’)
character.

What your example suggests is that you want to have an option, “-o”,
which takes an argument which is the output suffix. I'd prefer to also
have a long option with a descriptive name for the same purpose.

So here's my interpretation::

    >>> import optparse
    >>> parser = optparse.OptionParser()
    >>> parser.add_option(
    ...     "-o", "--output-suffix",
    ...     dest='out_suffix', metavar="SUFFIX",
    ...     help="Specify SUFFIX as the suffix of the output filename.")
    <Option at 0xf78d4350: -o/--output-suffix>
    >>> print parser.format_option_help()
    Options:
      -h, --help            show this help message and exit
      -o SUFFIX, --output-suffix=SUFFIX
                            Specify SUFFIX as the suffix of the output filename.

> Can you please suggest any other best way / optimized way to parse
> these kind of options.

For testing the above, I make use of the ‘shlex’ module to split a
command-line string into separate arguments as the OptionParser will
expect::

    >>> import shlex

The OptionParser instance, as the help message above explains, allows
the usual ways of specifying an argument to that option::

    >>> cmdline_args = shlex.split("fooprog -o .exe spam beans")
    >>> (opts, args) = parser.parse_args(cmdline_args[1:])
    >>> opts.out_suffix
    '.exe'

    >>> cmdline_args = shlex.split("fooprog -o.txt spam beans")
    >>> (opts, args) = parser.parse_args(cmdline_args[1:])
    >>> opts.out_suffix
    '.txt'

    >>> cmdline_args = shlex.split("fooprog --output-suffix .pdf spam beans")
    >>> (opts, args) = parser.parse_args(cmdline_args[1:])
    >>> opts.out_suffix
    '.pdf'

    >>> cmdline_args = shlex.split("fooprog --output-suffix=.ppt spam beans")
    >>> (opts, args) = parser.parse_args(cmdline_args[1:])
    >>> opts.out_suffix
    '.ppt'

-- 
 \      “I used to be a proofreader for a skywriting company.” —Steven |
  `\                                                            Wright |
_o__)                                                                  |
Ben Finney



More information about the Python-list mailing list