optparse options

Ben Finney ben+python at benfinney.id.au
Wed May 20 01:21:01 CEST 2009


icarus <rsarpi at gmail.com> writes:

> 	parser = optparse.OptionParser(usage="%prog [-p dir] [--part=dir] ",
> version="%prog 1.0")
> 
> 	parser.add_option( "-p", "--part", dest="directory",
> 	                  help="process target directory", metavar="dir")
> 	(options, args) = parser.parse_args()

As documented in ‘OptionParser.parse_args’, the return values are the
options parsed, and the *remaining* arguments after all the arguments
parsed as options.

So, the ‘args’ name will be bound to a list of only those arguments
which were not options. Very useful for programs which, in addition to
options, also take positional arguments where each argument position has
a specific meaning (e.g. “input_file output_file”).

> 	if len(args) != 1:
> 		parser.error("No options specified")

The message is confusing, since it doesn't match the condition; it would
be correct to say “Did not specify exactly one non-option argument”.

In this case, it looks like you don't want to check this at all, and
should instead operate on the basis of the options only.

-- 
 \          “There's a certain part of the contented majority who love |
  `\            anybody who is worth a billion dollars.” —John Kenneth |
_o__)                                            Galbraith, 1992-05-23 |
Ben Finney



More information about the Python-list mailing list