1 \section{\module{optparse
} ---
2 Powerful parser for command line options.
}
4 \declaremodule{standard
}{optparse
}
5 \moduleauthor{Greg Ward
}{gward@python.net
}
6 \sectionauthor{Johannes Gijsbers
}{jlgijsbers@users.sf.net
}
7 \sectionauthor{Greg Ward
}{gward@python.net
}
9 \modulesynopsis{Powerful, flexible, extensible, easy-to-use command-line
14 The
\module{optparse
} module is a powerful, flexible, extensible,
15 easy-to-use command-line parsing library for Python. Using
16 \module{optparse
}, you can add intelligent, sophisticated handling of
17 command-line options to your scripts with very little overhead.
19 Here's an example of using
\module{optparse
} to add some command-line
20 options to a simple script:
23 from optparse import OptionParser
25 parser = OptionParser()
26 parser.add_option("-f", "--file", dest="filename",
27 help="write
report to FILE", metavar="FILE")
28 parser.add_option("-q", "--quiet",
29 action="store_false", dest="verbose", default=
1,
30 help="don't print status messages to stdout")
32 (options, args) = parser.parse_args()
35 With these few lines of code, users of your script can now do the
36 "usual thing" on the command-line:
39 $ <yourscript> -f outfile --quiet
40 $ <yourscript> -qfoutfile
41 $ <yourscript> --file=outfile -q
42 $ <yourscript> --quiet --file outfile
45 (All of these result in
\code{options.filename == "outfile"
} and
46 \code{options.verbose ==
0} ...just as you might expect.)
48 Even niftier, users can run one of
53 and
\module{optparse
} will print out a brief summary of your script's
57 usage: <yourscript>
[options
]
60 -h, --help show this help message and exit
61 -fFILE, --file=FILE write
report to FILE
62 -q, --quiet don't print status messages to stdout
65 That's just a taste of the flexibility
\module{optparse
} gives you in
66 parsing your command-line.
68 \subsection{The Tao of Option Parsing
\label{optparse-tao
}}
70 \module{optparse
} is an implementation of what I have always
71 considered the most obvious, straightforward, and user-friendly way to
72 design a user interface for command-line programs. In short, I have
73 fairly firm ideas of the Right Way (and the many Wrong Ways) to do
74 argument parsing, and
\module{optparse
} reflects many of those ideas.
75 This section is meant to explain this philosophy, which in turn is
76 heavily influenced by the Unix and GNU toolkits.
78 \subsubsection{Terminology
\label{optparse-terminology
}}
80 First, we need to establish some terminology.
84 a chunk of text that a user enters on the command-line, and that the
85 shell passes to
\cfunction{execl()
} or
\cfunction{execv()
}. In
86 Python, arguments are elements of
87 \var{sys.argv
[1:
]}. (
\var{sys.argv
[0]} is the name of the program
88 being executed; in the context of parsing arguments, it's not very
89 important.) Unix shells also use the term ``word''.
91 It's occasionally desirable to substitute an argument list other
92 than
\var{sys.argv
[1:
]}, so you should read ``argument'' as ``an element of
93 \var{sys.argv
[1:
]}, or of some other list provided as a substitute for
97 an argument used to supply extra information to guide or customize
98 the execution of a program. There are many different syntaxes for
99 options; the traditional Unix syntax is
\programopt{-
} followed by a
100 single letter, e.g.
\programopt{-x
} or
\programopt{-F
}. Also,
101 traditional Unix syntax allows multiple options to be merged into a
102 single argument, e.g.
\programopt{-x -F
} is equivalent to
103 \programopt{-xF
}. The GNU project introduced
\longprogramopt{}
104 followed by a series of hyphen-separated words,
105 e.g.
\longprogramopt{file
} or
\longprogramopt{dry-run
}. These are
106 the only two option syntaxes provided by
\module{optparse
}.
108 Some other option syntaxes that the world has seen include:
111 \item a hyphen followed by a few letters, e.g.
\programopt{-pf
} (this is
112 *not* the same as multiple options merged into a single
114 \item a hyphen followed by a whole word, e.g.
\programopt{-file
} (this is
115 technically equivalent to the previous syntax, but they aren't
116 usually seen in the same program.)
117 \item a plus sign followed by a single letter, or a few letters,
118 or a word, e.g.
\programopt{+f
},
\programopt{+rgb
}.
119 \item a slash followed by a letter, or a few letters, or a word, e.g.
120 \programopt{/f
},
\programopt{/file
}.
123 These option syntaxes are not supported by
\module{optparse
}, and they
124 never will be. (If you really want to use one of those option
125 syntaxes, you'll have to subclass OptionParser and override all the
126 difficult bits. But please don't!
\module{optparse
} does things the
127 traditional Unix/GNU way deliberately; the first three are
128 non-standard anywhere, and the last one makes sense only if you're
129 exclusively targeting MS-DOS/Windows and/or VMS.)
131 \term{option argument
}
132 an argument that follows an option, is closely associated with that
133 option, and is consumed from the argument list when the option is.
134 Often, option arguments may also be included in the same argument as
141 may be equivalent to:
147 (
\module{optparse
} supports this syntax.)
149 Some options never take an argument. Some options always take an
150 argument. Lots of people want an ``optional option arguments'' feature,
151 meaning that some options will take an argument if they see it, and
152 won't if they don't. This is somewhat controversial, because it makes
153 parsing ambiguous: if
\programopt{-a
} takes an optional argument and
154 \programopt{-b
} is another option entirely, how do we interpret
155 \programopt{-ab
}?
\module{optparse
} does not currently support this.
157 \term{positional argument
}
158 something leftover in the argument list after options have been
159 parsed, ie. after options and their arguments have been parsed and
160 removed from the argument list.
162 \term{required option
}
163 an option that must be supplied on the command-line; the phrase
164 "required option" is an oxymoron and I personally consider it poor UI
165 design.
\module{optparse
} doesn't prevent you from implementing
166 required options, but doesn't give you much help at it either. See
167 Extending Examples (section
\ref{optparse-extending-examples
}) for two
168 ways to implement required options with
\module{optparse
}.
172 For example, consider this hypothetical command-line:
175 prog -v --
report /tmp/
report.txt foo bar
178 \programopt{-v
} and
\longprogramopt{report} are both options. Assuming
179 the
\longprogramopt{report} option takes one argument,
180 ``/tmp/
report.txt'' is an option argument. ``foo'' and ``bar'' are
181 positional arguments.
183 \subsubsection{What are options for?
\label{optparse-options
}}
185 Options are used to provide extra information to tune or customize the
186 execution of a program. In case it wasn't clear, options are usually
187 \emph{optional
}. A program should be able to run just fine with no
188 options whatsoever. (Pick a random program from the Unix or GNU
189 toolsets. Can it run without any options at all and still make sense?
190 The only exceptions I can think of are find, tar, and dd -- all of
191 which are mutant oddballs that have been rightly criticized for their
192 non-standard syntax and confusing interfaces.)
194 Lots of people want their programs to have ``required options''.
195 Think about it. If it's required, then it's
\emph{not optional
}! If
196 there is a piece of information that your program absolutely requires
197 in order to run successfully, that's what positional arguments are
198 for. (However, if you insist on adding ``required options'' to your
199 programs, look in Extending Examples (section
200 \ref{optparse-extending-examples
}) for two ways of implementing them
201 with
\module{optparse
}.)
203 Consider the humble
\program{cp
} utility, for copying files. It
204 doesn't make much sense to try to copy files without supplying a
205 destination and at least one source. Hence,
\program{cp
} fails if you
206 run it with no arguments. However, it has a flexible, useful syntax
207 that does not rely on options at all:
211 $ cp SOURCE ... DEST-DIR
214 You can get pretty far with just that. Most
\program{cp
}
215 implementations provide a bunch of options to tweak exactly how the
216 files are copied: you can preserve mode and modification time, avoid
217 following symlinks, ask before clobbering existing files, etc. But
218 none of this distracts from the core mission of
\program{cp
}, which is
219 to copy one file to another, or N files to another directory.
221 \subsubsection{What are positional arguments for?
\label{optparse-positional-arguments
}}
223 In case it wasn't clear from the above example: positional arguments
224 are for those pieces of information that your program absolutely,
225 positively requires to run.
227 A good user interface should have as few absolute requirements as
228 possible. If your program requires
17 distinct pieces of information in
229 order to run successfully, it doesn't much matter
\emph{how
} you get that
230 information from the user -- most people will give up and walk away
231 before they successfully run the program. This applies whether the user
232 interface is a command-line, a configuration file, a GUI, or whatever:
233 if you make that many demands on your users, most of them will just give
236 In short, try to minimize the amount of information that users are
237 absolutely required to supply -- use sensible defaults whenever
238 possible. Of course, you also want to make your programs reasonably
239 flexible. That's what options are for. Again, it doesn't matter if
240 they are entries in a config file, checkboxes in the ``Preferences''
241 dialog of a GUI, or command-line options -- the more options you
242 implement, the more flexible your program is, and the more complicated
243 its implementation becomes. It's quite easy to overwhelm users (and
244 yourself!) with too much flexibility, so be careful there.
246 \subsection{Basic Usage
\label{optparse-basic-usage
}}
248 While
\module{optparse
} is quite flexible and powerful, you don't have
249 to jump through hoops or read reams of documentation to get it working
250 in basic cases. This
document aims to demonstrate some simple usage
251 patterns that will get you started using
\module{optparse
} in your
254 To parse a command line with
\module{optparse
}, you must create an
255 \class{OptionParser
} instance and populate it. Obviously, you'll have
256 to import the
\class{OptionParser
} classes in any script that uses
260 from optparse import OptionParser
263 Early on in the main program, create a parser:
266 parser = OptionParser()
269 Then you can start populating the parser with options. Each option is
270 really a set of synonymous option strings; most commonly, you'll have
271 one short option string and one long option string --
272 e.g.
\programopt{-f
} and
\longprogramopt{file
}:
275 parser.add_option("-f", "--file", ...)
278 The interesting stuff, of course, is what comes after the option
279 strings. In this
document, we'll only cover four of the things you
280 can put there:
\var{action
},
\var{type
},
\var{dest
} (destination), and
283 \subsubsection{The "store" action
\label{optparse-store-action
}}
285 The action tells
\module{optparse
} what to do when it sees one of the
286 option strings for this option on the command-line. For example, the
287 action
\var{store
} means: take the next argument (or the remainder of
288 the current argument), ensure that it is of the correct type, and
289 store it to your chosen destination.
291 For example, let's fill in the "..." of that last option:
294 parser.add_option("-f", "--file",
295 action="store", type="string", dest="filename")
298 Now let's make up a fake command-line and ask
\module{optparse
} to
302 args =
["-f", "foo.txt"
]
303 (options, args) = parser.parse_args(args)
306 (Note that if you don't pass an argument list to
307 \function{parse_args()
}, it automatically uses
\var{sys.argv
[1:
]}.)
309 When
\module{optparse
} sees the
\programopt{-f
}, it sucks in the next
310 argument -- ``foo.txt'' -- and stores it in the
\var{filename
}
311 attribute of a special object. That object is the first return value
312 from
\programopt{parse_args()
}, so:
315 print options.filename
318 will print ``foo.txt''.
320 Other option types supported by
\module{optparse
} are ``int'' and
321 ``float''. Here's an option that expects an integer argument:
324 parser.add_option("-n", type="int", dest="num")
327 Note that I didn't supply a long option, which is perfectly acceptable.
328 I also didn't specify the action -- it defaults to ``store''.
330 Let's parse another fake command-line. This time, we'll jam the
331 option argument right up against the option --
\programopt{-n42
} (one
332 argument) is equivalent to
\programopt{-n
42} (two arguments). :
335 (options, args) = parser.parse_args(
["-n42"
])
341 Trying out the ``float'' type is left as an exercise for the reader.
343 If you don't specify a type,
\module{optparse
} assumes ``string''.
344 Combined with the fact that the default action is ``store'', that
345 means our first example can be a lot shorter:
348 parser.add_option("-f", "--file", dest="filename")
351 If you don't supply a destination,
\module{optparse
} figures out a
352 sensible default from the option strings: if the first long option
353 string is
\longprogramopt{foo-bar
}, then the default destination is
354 \var{foo_bar
}. If there are no long option strings,
355 \module{optparse
} looks at the first short option: the default
356 destination for
\programopt{-f
} is
\var{f
}.
358 Adding types is fairly easy; please refer to section
359 \ref{optparse-adding-types
}: Adding new types.
361 \subsubsection{Other "store_*" actions
\label{optparse-other-store-actions
}}
363 Flag options -- set a variable to true or false when a particular
364 option is seen -- are quite common.
\module{optparse
} supports them
365 with two separate actions, ``store_true'' and ``store_false''. For
366 example, you might have a
\var{verbose
} flag that is turned on with
367 \programopt{-v
} and off with
\programopt{-q
}:
370 parser.add_option("-v", action="store_true", dest="verbose")
371 parser.add_option("-q", action="store_false", dest="verbose")
374 Here we have two different options with the same destination, which is
375 perfectly OK. (It just means you have to be a bit careful when setting
376 default values -- see below.)
378 When
\module{optparse
} sees
\programopt{-v
} on the command line, it
379 sets the
\var{verbose
} attribute of the special
{option values
}
380 object to
1; when it sees
\programopt{-q
}, it sets
\var{verbose
} to
383 \subsubsection{Setting default values
\label{optparse-setting-default-values
}}
385 All of the above examples involve setting some variable (the
386 ``destination'') when certain command-line options are seen. What
387 happens if those options are never seen? Since we didn't supply any
388 defaults, they are all set to None. Sometimes, this is just fine
389 (which is why it's the default), but sometimes, you want more control.
390 To address that need,
\module{optparse
} lets you supply a default
391 value for each destination, which is assigned before the command-line
394 First, consider the verbose/quiet example. If we want
395 \module{optparse
} to set
\var{verbose
} to
1 unless -q is seen, then
399 parser.add_option("-v", action="store_true", dest="verbose", default=
1)
400 parser.add_option("-q", action="store_false", dest="verbose")
403 Oddly enough, this is exactly equivalent:
406 parser.add_option("-v", action="store_true", dest="verbose")
407 parser.add_option("-q", action="store_false", dest="verbose", default=
1)
410 Those are equivalent because you're supplying a default value for the
411 option's
\emph{destination
}, and these two options happen to have the same
412 destination (the
\var{verbose
} variable).
417 parser.add_option("-v", action="store_true", dest="verbose", default=
0)
418 parser.add_option("-q", action="store_false", dest="verbose", default=
1)
421 Again, the default value for
\var{verbose
} will be
1: the last
422 default value supplied for any particular destination attribute is the
425 \subsubsection{Generating help
\label{optparse-generating-help
}}
427 The last feature that you will use in every script is
428 \module{optparse
}'s ability to generate help messages. All you have
429 to do is supply a
\var{help
} value when you add an option. Let's
430 create a new parser and populate it with user-friendly (documented)
434 usage = "usage:
%prog [options] arg1 arg2"
435 parser = OptionParser(usage=usage)
436 parser.add_option("-v", "--verbose",
437 action="store_true", dest="verbose", default=
1,
438 help="make lots of noise
[default
]")
439 parser.add_option("-q", "--quiet",
440 action="store_false", dest="verbose",
441 help="be vewwy quiet (I'm hunting wabbits)")
442 parser.add_option("-f", "--file", dest="filename",
443 metavar="FILE", help="write output to FILE"),
444 parser.add_option("-m", "--mode",
445 default="intermediate",
446 help="interaction mode: one of 'novice', "
447 "'intermediate'
[default
], 'expert'")
450 If
\module{optparse
} encounters either
\programopt{-h
} or
451 \longprogramopt{--help
} on the command-line, or if you just call
452 \method{parser.print_help()
}, it prints the following to stdout:
455 usage: <yourscript>
[options
] arg1 arg2
458 -h, --help show this help message and exit
459 -v, --verbose make lots of noise
[default
]
460 -q, --quiet be vewwy quiet (I'm hunting wabbits)
461 -fFILE, --file=FILE write output to FILE
462 -mMODE, --mode=MODE interaction mode: one of 'novice', 'intermediate'
466 There's a lot going on here to help
\module{optparse
} generate the
467 best possible help message:
470 \item the script defines its own usage message:
473 usage = "usage:
%prog [options] arg1 arg2"
476 \module{optparse
} expands "\%prog" in the usage string to the name of the
477 current script, ie.
\code{os.path.basename(sys.argv
[0])
}. The
478 expanded string is then printed before the detailed option help.
480 If you don't supply a usage string,
\module{optparse
} uses a bland but
481 sensible default: ``usage: \%prog
[options
]'', which is fine if your
482 script doesn't take any positional arguments.
484 \item every option defines a help string, and doesn't worry about
485 line-wrapping --
\module{optparse
} takes care of wrapping lines and
486 making the help output look good.
488 \item options that take a value indicate this fact in their
489 automatically-generated help message, e.g. for the ``mode'' option:
495 Here, ``MODE'' is called the meta-variable: it stands for the argument
496 that the user is expected to supply to
497 \programopt{-m
}/
\longprogramopt{mode
}. By default,
\module{optparse
}
498 converts the destination variable name to uppercase and uses that for
499 the meta-variable. Sometimes, that's not what you want -- for
500 example, the
\var{filename
} option explicitly sets
501 \code{metavar="FILE"
}, resulting in this automatically-generated
508 This is important for more than just saving space, though: the
509 manually written help text uses the meta-variable ``FILE'', to clue
510 the user in that there's a connection between the formal syntax
511 ``-fFILE'' and the informal semantic description ``write output to
512 FILE''. This is a simple but effective way to make your help text a
513 lot clearer and more useful for end users.
516 \subsubsection{Print a version number
\label{optparse-print-version
}}
518 Similar to the brief usage string,
\module{optparse
} can also print a
519 version string for your program. You have to supply the string, as
520 the
\var{version
} argument to
\class{OptionParser
}:
523 parser = OptionParser(usage="
%prog [-f] [-q]", version="%prog 1.0")
526 Note that ``\%prog'' is expanded just like it is in
\var{usage
}. Apart from
527 that,
\var{version
} can contain anything you like. When you supply it,
528 \module{optparse
} automatically adds a\ longprogramopt
{version
} option to your
529 parser. If it encounters this option on the command line, it expands
530 your
\var{version
} string (by replacing ``\%prog''), prints it to
533 For example, if your script is called /usr/bin/foo, a user might do:
536 $ /usr/bin/foo --version
541 \subsubsection{Error-handling
\label{optparse-error-handling
}}
543 The one thing you need to know for basic usage is how
544 \module{optparse
} behaves when it encounters an error on the
545 command-line -- e.g.
\programopt{-n4x
} where
\programopt{-n
} is an
546 integer-valued option.
\module{optparse
} prints your usage message to
547 stderr, followed by a useful and human-readable error message. Then
548 it terminates (calls
\function{sys.exit()
}) with a non-zero exit
551 If you don't like this, subclass
\class{OptionParser
} and override the
552 \method{error()
} method. See section
\ref{optparse-extending
}:
553 Extending
\module{optparse
}.
555 \subsubsection{Putting it all together
\label{optparse-basic-summary
}}
557 Here's what my
\module{optparse
}-based scripts usually look like:
560 from optparse import OptionParser
565 usage = "usage:
%prog [options] arg"
566 parser = OptionParser(usage)
567 parser.add_option("-f", "--file", type="string", dest="filename",
568 help="read data from FILENAME")
569 parser.add_option("-v", "--verbose",
570 action="store_true", dest="verbose")
571 parser.add_option("-q", "--quiet",
572 action="store_false", dest="verbose")
573 [... more options ...
]
575 (options, args) = parser.parse_args()
577 parser.error("incorrect number of arguments")
580 print "reading
%s..." % options.filename
584 if __name__ == "__main__":
588 \subsection{Advanced Usage
\label{optparse-advanced-usage
}}
590 This is reference documentation. If you haven't read the basic
591 documentation in section
\ref{optparse-basic-usage
}, do so now.
593 \subsubsection{Creating and populating the parser
\label{optparse-creating-the-parser
}}
595 There are several ways to populate the parser with options. One way
596 is to pass a list of
\class{Options
} to the
\class{OptionParser
}
600 parser = OptionParser(option_list=
[
601 make_option("-f", "--filename",
602 action="store", type="string", dest="filename"),
603 make_option("-q", "--quiet",
604 action="store_false", dest="verbose")
])
607 (As of
\module{optparse
} 1.3,
\function{make_option()
} is an alias for
608 the
\class{Option
} class, ie. this just calls the
\class{Option
}
609 constructor. A future version of
\module{optparse
} will probably
610 split
\class{Option
} into several classes, and
611 \function{make_option()
} will become a factory function that picks the
612 right class to instantiate.)
614 For long option lists, it's often more convenient/readable to create the
618 option_list =
[make_option("-f", "--filename",
619 action="store", type="string", dest="filename"),
620 # ...
17 other options ...
621 make_option("-q", "--quiet",
622 action="store_false", dest="verbose")
]
623 parser = OptionParser(option_list=option_list)
626 Or, you can use the
\method{add_option()
} method of
627 \class{OptionParser
} to add options one-at-a-time:
630 parser = OptionParser()
631 parser.add_option("-f", "--filename",
632 action="store", type="string", dest="filename")
633 parser.add_option("-q", "--quiet",
634 action="store_false", dest="verbose")
637 This method makes it easier to track down exceptions raised by the
638 \class{Option
} constructor, which are common because of the complicated
639 interdependencies among the various keyword arguments -- if you get it
640 wrong,
\module{optparse
} raises
\exception{OptionError
}.
642 \method{add_option()
} can be called in one of two ways:
645 \item pass it an
\class{Option
} instance (as returned by
\function{make_option()
})
646 \item pass it any combination of positional and keyword arguments that
647 are acceptable to
\function{make_option()
} (ie., to the
\class{Option
}
648 constructor), and it will create the
\class{Option
} instance for you
652 \subsubsection{Defining options
\label{optparse-defining-options
}}
654 Each
\class{Option
} instance represents a set of synonymous
655 command-line options, ie. options that have the same meaning and
656 effect, but different spellings. You can specify any number of short
657 or long option strings, but you must specify at least one option
660 To define an option with only a short option string:
663 make_option("-f", ...)
666 And to define an option with only a long option string:
669 make_option("--foo", ...)
672 The ``...'' represents a set of keyword arguments that define
673 attributes of the
\class{Option
} object. Just which keyword args you
674 must supply for a given
\class{Option
} is fairly complicated (see the
675 various
\method{_check_*()
} methods in the
\class{Option
} class if you
676 don't believe me), but you always have to supply
\emph{some
}. If you
677 get it wrong,
\module{optparse
} raises an
\exception{OptionError
}
678 exception explaining your mistake.
680 The most important attribute of an option is its action, ie. what to do
681 when we encounter this option on the command-line. The possible actions
685 \term{store
} [default
]
686 store this option's argument.
688 store a constant value.
694 append this option's argument to a list.
696 increment a counter by one.
698 call a specified function.
700 print a usage message including all options and the documentation for
704 (If you don't supply an action, the default is ``store''. For this
705 action, you may also supply
\var{type
} and
\var{dest
} keywords; see
708 As you can see, most actions involve storing or updating a value
709 somewhere.
\module{optparse
} always creates a particular object (an
710 instance of the
\class{Values
} class) specifically for this
711 purpose. Option arguments (and various other values) are stored as
712 attributes of this object, according to the
\var{dest
} (destination)
713 argument to
\function{make_option()
}/
\method{add_option()
}.
715 For example, when you call:
721 one of the first things
\module{optparse
} does is create a
728 If one of the options in this parser is defined with:
731 make_option("-f", "--file", action="store", type="string", dest="filename")
734 and the command-line being parsed includes any of the following:
743 then
\module{optparse
}, on seeing the
\programopt{-f
} or
744 \longprogramopt{file
} option, will do the equivalent of this:
747 values.filename = "foo"
750 Clearly, the
\var{type
} and
\var{dest
} arguments are (usually) almost
751 as important as
\var{action
}.
\var{action
} is the only attribute that
752 is meaningful for *all* options, though, so it is the most important.
754 \subsubsection{Option actions
\label{optparse-option-actions
}}
756 The various option actions all have slightly different requirements
757 and effects. Except for the ``help'' action, you must supply at least
758 one other keyword argument when creating the
\class{Option
}; the exact
759 requirements for each action are listed here.
762 \term{store
} [relevant:
\var{type
},
\var{dest
},
\var{nargs
},
\var{choices
}]
764 The option must be followed by an argument, which is converted to a
765 value according to
\var{type
} and stored in
\var{dest
}. If
766 \var{nargs
} >
1, multiple arguments will be consumed from the command
767 line; all will be converted according to
\var{type
} and stored to
768 \var{dest
} as a tuple. See section
\ref{optparse-option-types
}:
771 If
\var{choices
} is supplied (a list or tuple of strings), the type
772 defaults to ``choice''.
774 If
\var{type
} is not supplied, it defaults to ``string''.
776 If
\var{dest
} is not supplied,
\module{optparse
} derives a
777 destination from the first long option strings (e.g.,
778 \longprogramopt{foo-bar
} ->
\var{foo_bar
}). If there are no long
779 option strings,
\module{optparse
} derives a destination from the first
780 short option string (e.g.,
\programopt{-f
} ->
\var{f
}).
786 make_option("-p", type="float", nargs=
3, dest="point")
789 Given the following command line:
792 -f foo.txt -p
1 -
3.5 4 -fbar.txt
795 \module{optparse
} will set:
799 values.point = (
1.0, -
3.5,
4.0)
802 (Actually,
\member{values.f
} will be set twice, but only the second
803 time is visible in the end.)
805 \term{store_const
} [required:
\var{const
},
\var{dest
}]
807 The
\var{const
} value supplied to the
\class{Option
} constructor is
808 stored in
\var{dest
}.
813 make_option("-q", "--quiet",
814 action="store_const", const=
0, dest="verbose"),
815 make_option("-v", "--verbose",
816 action="store_const", const=
1, dest="verbose"),
817 make_option(None, "--noisy",
818 action="store_const", const=
2, dest="verbose"),
821 If
\longprogramopt{noisy
} is seen,
\module{optparse
} will set:
827 \term{store_true
} [required:
\var{dest
}]
829 A special case of ``store_const'' that stores a true value
830 (specifically, the integer
1) to
\var{dest
}.
832 \term{store_false
} [required:
\var{dest
}]
834 Like ``store_true'', but stores a false value (the integer
0).
839 make_option(None, "--clobber", action="store_true", dest="clobber")
840 make_option(None, "--no-clobber", action="store_false", dest="clobber")
843 \term{append
} [relevant:
\var{type
},
\var{dest
},
\var{nargs
},
\var{choices
}]
845 The option must be followed by an argument, which is appended to the
846 list in
\var{dest
}. If no default value for
\var{dest
} is supplied
847 (ie. the default is None), an empty list is automatically created when
848 \module{optparse
} first encounters this option on the command-line.
849 If
\samp{nargs >
1}, multiple arguments are consumed, and a tuple of
850 length
\var{nargs
} is appended to
\var{dest
}.
852 The defaults for
\var{type
} and
\var{dest
} are the same as for the
858 make_option("-t", "--tracks", action="append", type="int")
861 If
\programopt{-t3
} is seen on the command-line,
\module{optparse
} does the equivalent of:
865 values.tracks.append(int("
3"))
868 If, a little later on,
\samp{--tracks=
4} is seen, it does:
871 values.tracks.append(int("
4"))
874 See Error handling (section
\ref{optparse-error-handling
}) for
875 information on how
\module{optparse
} deals with something like
878 \term{count
} [required:
\var{dest
}]
880 Increment the integer stored at
\var{dest
}.
\var{dest
} is set to zero
881 before being incremented the first time (unless you supply a default
887 make_option("-v", action="count", dest="verbosity")
890 The first time
\programopt{-v
} is seen on the command line,
891 \module{optparse
} does the equivalent of:
895 values.verbosity +=
1
898 Every subsequent occurrence of
\programopt{-v
} results in:
901 values.verbosity +=
1
904 \term{callback
} [required:
\var{'callback'
};
905 relevant:
\var{type
},
\var{nargs
},
\var{callback_args
},
906 \var{callback_kwargs
}]
908 Call the function specified by
\var{callback
}. The signature of
909 this function should be:
912 func(option : Option,
915 parser : OptionParser,
919 Callback options are covered in detail in section
920 \ref{optparse-callback-options
}: Callback Options.
922 \term{help
} [required: none
]
924 Prints a complete help message for all the options in the current
925 option parser. The help message is constructed from the
\var{usage
}
926 string passed to
\class{OptionParser
}'s constructor and the
\var{help
}
927 string passed to every option.
929 If no
\var{help
} string is supplied for an option, it will still be
930 listed in the help message. To omit an option entirely, use the
931 special value
\constant{optparse.SUPPRESS_HELP
}.
936 from optparse import Option, OptionParser, SUPPRESS_HELP
938 usage = "usage:
%prog [options]"
939 parser = OptionParser(usage, option_list=
[
940 make_option("-h", "--help", action="help"),
941 make_option("-v", action="store_true", dest="verbose",
942 help="Be moderately verbose")
943 make_option("--file", dest="filename",
944 help="Input file to read data from"),
945 make_option("--secret", help=SUPPRESS_HELP)
948 If
\module{optparse
} sees either
\longprogramopt{-h
} or
\longprogramopt{help
} on
949 the command line, it will print something like the following help
953 usage: <yourscript>
[options
]
956 -h, --help Show this help message and exit
957 -v Be moderately verbose
958 --file=FILENAME Input file to read data from
961 After printing the help message,
\module{optparse
} terminates your process
962 with
\code{sys.exit(
0)
}.
964 \term{version
} [required: none
]
966 Prints the version number supplied to the
\class{OptionParser
} to
967 stdout and exits. The version number is actually formatted and
968 printed by the
\method{print_version()
} method of
969 \class{OptionParser
}. Generally only relevant if the
\var{version
}
970 argument is supplied to the
\class{OptionParser
} constructor.
973 \subsubsection{Option types
\label{optparse-option-types
}}
975 \module{optparse
} supports six option types out of the box:
\dfn{string
},
976 \dfn{int
},
\dfn{long
},
\dfn{choice
},
\dfn{float
} and
\dfn{complex
}.
977 (Of these, string, int, float, and choice are the most commonly used
978 -- long and complex are there mainly for completeness.) It's easy to
979 add new option types by subclassing the
\class{Option
} class; see
980 section
\ref{optparse-extending
}: Extending
\module{optparse
}.
982 Arguments to string options are not checked or converted in any way:
983 the text on the command line is stored in the destination (or passed
984 to the callback) as-is.
986 Integer arguments are passed to
\function{int()
} to convert them to
987 Python integers. If
\function{int()
} fails, so will
988 \module{optparse
}, although with a more useful error message.
989 Internally,
\module{optparse
} raises
\exception{OptionValueError
} in
990 \function{optparse.check_builtin()
}; at a higher level (in
991 \class{OptionParser
}) this is caught and
\module{optparse
} terminates
992 your program with a useful error message.
994 Likewise, float arguments are passed to
\function{float()
} for
995 conversion, long arguments to
\function{long()
}, and complex arguments
996 to
\function{complex()
}. Apart from that, they are handled
997 identically to integer arguments.
999 Choice options are a subtype of string options. A master list or
1000 tuple of choices (strings) must be passed to the option constructor
1001 (
\function{make_option()
} or
\method{OptionParser.add_option()
}) as
1002 the ``choices'' keyword argument. Choice option arguments are
1003 compared against this master list in
1004 \function{optparse.check_choice()
}, and
\exception{OptionValueError
}
1005 is raised if an unknown string is given.
1007 \subsubsection{Querying and manipulating your option parser
\label{optparse-querying-and-manipulating
}}
1009 Sometimes, it's useful to poke around your option parser and see what's
1010 there.
\class{OptionParser
} provides a couple of methods to help you out:
1012 \begin{methoddesc
}{has_option
}{opt_str
}
1013 Given an option string such as
\programopt{-q
} or
1014 \longprogramopt{verbose
}, returns true if the
\class{OptionParser
}
1015 has an option with that option string.
1018 \begin{methoddesc
}{get_option
}{opt_str
}
1019 Returns the
\class{Option
} instance that implements the option
1020 string you supplied, or None if no options implement it.
1023 \begin{methoddesc
}{remove_option
}{opt_str
}
1024 If the
\class{OptionParser
} has an option corresponding to
1025 \var{opt_str
}, that option is removed. If that option provided
1026 any other option strings, all of those option strings become
1029 If
\var{opt_str
} does not occur in any option belonging to this
1030 \class{OptionParser
}, raises
\exception{ValueError
}.
1033 \subsubsection{Conflicts between options
\label{optparse-conflicts
}}
1035 If you're not careful, it's easy to define conflicting options:
1038 parser.add_option("-n", "--dry-run", ...)
1040 parser.add_option("-n", "--noisy", ...)
1043 (This is even easier to do if you've defined your own
1044 \class{OptionParser
} subclass with some standard options.)
1046 On the assumption that this is usually a mistake,
\module{optparse
}
1047 1.2 and later raise an exception (
\exception{OptionConflictError
}) by
1048 default when this happens. Since this is an easily-fixed programming
1049 error, you shouldn't try to catch this exception -- fix your mistake
1050 and get on with life.
1052 Sometimes, you want newer options to deliberately replace the option
1053 strings used by older options. You can achieve this by calling:
1056 parser.set_conflict_handler("resolve")
1059 which instructs
\module{optparse
} to resolve option conflicts
1062 Here's how it works: every time you add an option,
\module{optparse
}
1063 checks for conflicts with previously-added options. If it finds any,
1064 it invokes the conflict-handling mechanism you specify either to the
1065 \class{OptionParser
} constructor:
1068 parser = OptionParser(..., conflict_handler="resolve")
1071 or via the
\method{set_conflict_handler()
} method.
1073 The default conflict-handling mechanism is ``error''. The only other
1074 one is ``ignore'', which restores the (arguably broken) behaviour of
1075 \module{optparse
} 1.1 and earlier.
1077 Here's an example: first, define an
\class{OptionParser
} set to
1078 resolve conflicts intelligently:
1081 parser = OptionParser(conflict_handler="resolve")
1084 Now add all of our options:
1087 parser.add_option("-n", "--dry-run", ..., help="original dry-run option")
1089 parser.add_option("-n", "--noisy", ..., help="be noisy")
1092 At this point,
\module{optparse
} detects that a previously-added option is already
1093 using the
\programopt{-n
} option string. Since
\code{conflict_handler
1094 == "resolve"
}, it resolves the situation by removing
\programopt{-n
}
1095 from the earlier option's list of option strings. Now,
1096 \longprogramopt{dry-run
} is the only way for the user to activate that
1097 option. If the user asks for help, the help message will reflect
1102 --dry-run original dry-run option
1104 -n, --noisy be noisy
1107 Note that it's possible to whittle away the option strings for a
1108 previously-added option until there are none left, and the user has no
1109 way of invoking that option from the command-line. In that case,
1110 \module{optparse
} removes that option completely, so it doesn't show
1111 up in help text or anywhere else. E.g. if we carry on with our
1112 existing
\class{OptionParser
}:
1115 parser.add_option("--dry-run", ..., help="new dry-run option")
1118 At this point, the first
\programopt{-n
}/
\longprogramopt{dry-run
}
1119 option is no longer accessible, so
\module{optparse
} removes it. If
1120 the user asks for help, they'll get something like this:
1125 -n, --noisy be noisy
1126 --dry-run new dry-run option
1129 \subsection{Callback Options
\label{optparse-callback-options
}}
1131 If
\module{optparse
}'s built-in actions and types just don't fit the
1132 bill for you, but it's not worth extending
\module{optparse
} to define
1133 your own actions or types, you'll probably need to define a callback
1134 option. Defining callback options is quite easy; the tricky part is
1135 writing a good callback (the function that is called when
1136 \module{optparse
} encounters the option on the command line).
1138 \subsubsection{Defining a callback option
\label{optparse-defining-callback-option
}}
1140 As always, you can define a callback option either by directly
1141 instantiating the
\class{Option
} class, or by using the
1142 \method{add_option()
} method of your
\class{OptionParser
} object. The
1143 only option attribute you must specify is
\var{callback
}, the function
1147 parser.add_option("-c", callback=my_callback)
1150 Note that you supply a function object here -- so you must have
1151 already defined a function
\function{my_callback()
} when you define
1152 the callback option. In this simple case,
\module{optparse
} knows
1153 nothing about the arguments the
\programopt{-c
} option expects to
1154 take. Usually, this means that the option doesn't take any arguments
1155 -- the mere presence of
\programopt{-c
} on the command-line is all it
1156 needs to know. In some circumstances, though, you might want your
1157 callback to consume an arbitrary number of command-line arguments.
1158 This is where writing callbacks gets tricky; it's covered later in
1161 There are several other option attributes that you can supply when you
1162 define an option attribute:
1166 has its usual meaning: as with the ``store'' or ``append'' actions, it
1167 instructs
\module{optparse
} to consume one argument that must be
1168 convertible to
\var{type
}. Rather than storing the value(s) anywhere,
1169 though,
\module{optparse
} converts it to
\var{type
} and passes it to
1170 your callback function.
1173 also has its usual meaning: if it is supplied and
\samp{nargs >
1},
1174 \module{optparse
} will consume
\var{nargs
} arguments, each of which
1175 must be convertible to
\var{type
}. It then passes a tuple of
1176 converted values to your callback.
1178 \term{callback_args
}
1179 a tuple of extra positional arguments to pass to the callback.
1181 \term{callback_kwargs
}
1182 a dictionary of extra keyword arguments to pass to the callback.
1185 \subsubsection{How callbacks are called
\label{optparse-callbacks-called
}}
1187 All callbacks are called as follows:
1190 func(option, opt, value, parser, *args, **kwargs)
1197 is the
\class{Option
} instance that's calling the callback.
1200 is the option string seen on the command-line that's triggering the
1201 callback. (If an abbreviated long option was used,
\var{opt
} will be
1202 the full, canonical option string -- e.g. if the user puts
1203 \longprogramopt{foo
} on the command-line as an abbreviation for
1204 \longprogramopt{foobar
}, then
\var{opt
} will be
1205 \longprogramopt{foobar
}.)
1208 is the argument to this option seen on the command-line.
1209 \module{optparse
} will only expect an argument if
\var{type
} is
1210 set; the type of
\var{value
} will be the type implied by the
1211 option's type (see
\ref{optparse-option-types
}: Option types). If
1212 \var{type
} for this option is None (no argument expected), then
1213 \var{value
} will be None. If
\samp{nargs >
1},
\var{value
} will
1214 be a tuple of values of the appropriate type.
1217 is the
\class{OptionParser
} instance driving the whole thing, mainly
1218 useful because you can access some other interesting data through it,
1219 as instance attributes:
1223 the current remaining argument list, ie. with
\var{opt
} (and
1224 \var{value
}, if any) removed, and only the arguments following
1225 them still there. Feel free to modify
\member{parser.rargs
},
1226 e.g. by consuming more arguments.
1229 the current set of leftover arguments, ie. arguments that have been
1230 processed but have not been consumed as options (or arguments to
1231 options). Feel free to modify
\member{parser.largs
} e.g. by adding
1232 more arguments to it.
1234 \term{parser.values
}
1235 the object where option values are by default stored. This is useful
1236 because it lets callbacks use the same mechanism as the rest of
1237 \module{optparse
} for storing option values; you don't need to mess
1238 around with globals or closures. You can also access the value(s) of
1239 any options already encountered on the command-line.
1243 is a tuple of arbitrary positional arguments supplied via the
1244 \var{callback
}_args option attribute.
1247 is a dictionary of arbitrary keyword arguments supplied via
1248 \var{callback_kwargs
}.
1251 Since
\var{args
} and
\var{kwargs
} are optional (they are only passed
1252 if you supply
\var{callback_args
} and/or
\var{callback_kwargs
} when
1253 you define your callback option), the minimal callback function is:
1256 def my_callback (option, opt, value, parser):
1260 \subsubsection{Error handling
\label{optparse-callback-error-handling
}}
1262 The callback function should raise
\exception{OptionValueError
} if
1263 there are any problems with the option or its
1264 argument(s).
\module{optparse
} catches this and terminates the
1265 program, printing the error message you supply to stderr. Your
1266 message should be clear, concise, accurate, and mention the option at
1267 fault. Otherwise, the user will have a hard time figuring out what he
1270 \subsubsection{Examples
\label{optparse-callback-examples
}}
1272 Here's an example of a callback option that takes no arguments, and
1273 simply records that the option was seen:
1276 def record_foo_seen (option, opt, value, parser):
1279 parser.add_option("--foo", action="callback", callback=record_foo_seen)
1282 Of course, you could do that with the ``store_true'' action. Here's a
1283 slightly more interesting example: record the fact that
1284 \programopt{-a
} is seen, but blow up if it comes after
\programopt{-b
}
1285 in the command-line.
1288 def check_order (option, opt, value, parser):
1290 raise OptionValueError("can't use -a after -b")
1293 parser.add_option("-a", action="callback", callback=check_order)
1294 parser.add_option("-b", action="store_true", dest="b")
1297 If you want to reuse this callback for several similar options (set a
1298 flag, but blow up if
\programopt{-b
} has already been seen), it needs
1299 a bit of work: the error message and the flag that it sets must be
1303 def check_order (option, opt, value, parser):
1305 raise OptionValueError("can't use
%s after -b" % opt)
1306 setattr(parser.values, option.dest,
1)
1308 parser.add_option("-a", action="callback", callback=check_order, dest='a')
1309 parser.add_option("-b", action="store_true", dest="b")
1310 parser.add_option("-c", action="callback", callback=check_order, dest='c')
1313 Of course, you could put any condition in there -- you're not limited
1314 to checking the values of already-defined options. For example, if
1315 you have options that should not be called when the moon is full, all
1316 you have to do is this:
1319 def check_moon (option, opt, value, parser):
1321 raise OptionValueError("
%s option invalid when moon full" % opt)
1322 setattr(parser.values, option.dest,
1)
1324 parser.add_option("--foo",
1325 action="callback", callback=check_moon, dest="foo")
1328 (The definition of is_full_moon() is left as an exercise for the
1331 \strong{Fixed arguments
}
1333 Things get slightly more interesting when you define callback options
1334 that take a fixed number of arguments. Specifying that a callback
1335 option takes arguments is similar to defining a ``store'' or
1336 ``append'' option: if you define
\var{type
}, then the option takes one
1337 argument that must be convertible to that type; if you further define
1338 \var{nargs
}, then the option takes that many arguments.
1340 Here's an example that just emulates the standard ``store'' action:
1343 def store_value (option, opt, value, parser):
1344 setattr(parser.values, option.dest, value)
1346 parser.add_option("--foo",
1347 action="callback", callback=store_value,
1348 type="int", nargs=
3, dest="foo")
1351 Note that
\module{optparse
} takes care of consuming
3 arguments and
1352 converting them to integers for you; all you have to do is store them.
1353 (Or whatever: obviously you don't need a callback for this example.
1354 Use your imagination!)
1356 \strong{Variable arguments
}
1358 Things get hairy when you want an option to take a variable number of
1359 arguments. For this case, you have to write a callback;
1360 \module{optparse
} doesn't provide any built-in capabilities for it.
1361 You have to deal with the full-blown syntax for conventional Unix
1362 command-line parsing. (Previously,
\module{optparse
} took care of
1363 this for you, but I got it wrong. It was fixed at the cost of making
1364 this kind of callback more complex.) In particular, callbacks have to
1365 worry about bare
\longprogramopt{} and
\programopt{-
} arguments; the
1369 \item bare
\longprogramopt{}, if not the argument to some option,
1370 causes command-line processing to halt and the
\longprogramopt{}
1373 \item bare
\programopt{-
} similarly causes command-line processing to
1374 halt, but the
\programopt{-
} itself is kept.
1376 \item either
\longprogramopt{} or
\programopt{-
} can be option
1380 If you want an option that takes a variable number of arguments, there
1381 are several subtle, tricky issues to worry about. The exact
1382 implementation you choose will be based on which trade-offs you're
1383 willing to make for your application (which is why
\module{optparse
}
1384 doesn't support this sort of thing directly).
1386 Nevertheless, here's a stab at a callback for an option with variable
1390 def varargs (option, opt, value, parser):
1391 assert value is None
1394 rargs = parser.rargs
1398 # Stop if we hit an arg like "--foo", "-a", "-fx", "--file=f",
1399 # etc. Note that this also stops on "-
3" or "-
3.0", so if
1400 # your option takes numeric values, you will need to handle
1402 if ((arg
[:
2] == "--" and len(arg) >
2) or
1403 (arg
[:
1] == "-" and len(arg) >
1 and arg
[1] != "-")):
1409 setattr(parser.values, option.dest, value)
1412 parser.add_option("-c", "--callback",
1413 action="callback", callback=varargs)
1416 The main weakness with this particular implementation is that negative
1417 numbers in the arguments following
\programopt{-c
} will be interpreted
1418 as further options, rather than as arguments to
\programopt{-c
}.
1419 Fixing this is left as an exercise for the reader.
1421 \subsection{Extending
\module{optparse
}\label{optparse-extending
}}
1423 Since the two major controlling factors in how
\module{optparse
}
1424 interprets command-line options are the action and type of each
1425 option, the most likely direction of extension is to add new actions
1428 Also, the examples section includes several demonstrations of
1429 extending
\module{optparse
} in different ways: eg. a case-insensitive
1430 option parser, or two kinds of option parsers that implement
1431 ``required options''.
1433 \subsubsection{Adding new types
\label{optparse-adding-types
}}
1435 To add new types, you need to define your own subclass of
1436 \module{optparse
}'s
\class{Option
} class. This class has a couple of
1437 attributes that define
\module{optparse
}'s types:
\member{TYPES
} and
1438 \member{TYPE_CHECKER
}.
1440 \member{TYPES
} is a tuple of type names; in your subclass, simply
1441 define a new tuple
\member{TYPES
} that builds on the standard one.
1443 \member{TYPE_CHECKER
} is a dictionary mapping type names to
1444 type-checking functions. A type-checking function has the following
1448 def check_foo (option : Option, opt : string, value : string)
1452 You can name it whatever you like, and make it return any type you
1453 like. The value returned by a type-checking function will wind up in
1454 the
\class{OptionValues
} instance returned by
1455 \method{OptionParser.parse_args()
}, or be passed to callbacks as the
1456 \var{value
} parameter.
1458 Your type-checking function should raise
\exception{OptionValueError
}
1459 if it encounters any problems.
\exception{OptionValueError
} takes a
1460 single string argument, which is passed as-is to
1461 \class{OptionParser
}'s
\method{error()
} method, which in turn prepends
1462 the program name and the string ``error:'' and prints everything to
1463 stderr before terminating the process.
1465 Here's a silly example that demonstrates adding a ``complex'' option
1466 type to parse Python-style complex numbers on the command line. (This
1467 is even sillier than it used to be, because
\module{optparse
} 1.3 adds
1468 built-in support for complex numbers
[purely for completeness
], but
1471 First, the necessary imports:
1474 from copy import copy
1475 from optparse import Option, OptionValueError
1478 You need to define your type-checker first, since it's referred to
1479 later (in the
\member{TYPE_CHECKER
} class attribute of your
1480 \class{Option
} subclass):
1483 def check_complex (option, opt, value):
1485 return complex(value)
1487 raise OptionValueError(
1488 "option
%s: invalid complex value: %r" % (opt, value))
1491 Finally, the
\class{Option
} subclass:
1494 class MyOption (Option):
1495 TYPES = Option.TYPES + ("complex",)
1496 TYPE_CHECKER = copy(Option.TYPE_CHECKER)
1497 TYPE_CHECKER
["complex"
] = check_complex
1500 (If we didn't make a
\function{copy()
} of
1501 \member{Option.TYPE_CHECKER
}, we would end up modifying the
1502 \member{TYPE_CHECKER
} attribute of
\module{optparse
}'s Option class.
1503 This being Python, nothing stops you from doing that except good
1504 manners and common sense.)
1506 That's it! Now you can write a script that uses the new option type
1507 just like any other
\module{optparse
}-based script, except you have to
1508 instruct your
\class{OptionParser
} to use
\class{MyOption
} instead of
1512 parser = OptionParser(option_class=MyOption)
1513 parser.add_option("-c", action="store", type="complex", dest="c")
1516 Alternately, you can build your own option list and pass it to
1517 \class{OptionParser
}; if you don't use
\method{add_option()
} in the
1518 above way, you don't need to tell
\class{OptionParser
} which option
1522 option_list =
[MyOption("-c", action="store", type="complex", dest="c")
]
1523 parser = OptionParser(option_list=option_list)
1526 \subsubsection{Adding new actions
\label{optparse-adding-actions
}}
1528 Adding new actions is a bit trickier, because you have to understand
1529 that
\module{optparse
} has a couple of classifications for actions:
1532 \term{"store" actions
}
1533 actions that result in
\module{optparse
} storing a value to an attribute
1534 of the OptionValues instance; these options require a 'dest'
1535 attribute to be supplied to the Option constructor
1536 \term{"typed" actions
}
1537 actions that take a value from the command line and expect it to be
1538 of a certain type; or rather, a string that can be converted to a
1539 certain type. These options require a 'type' attribute to the
1543 Some default ``store'' actions are ``store'', ``store_const'',
1544 ``append'', and ``count''. The default ``typed'' actions are
1545 ``store'', ``append'', and ``callback''.
1547 When you add an action, you need to decide if it's a ``store'' action,
1548 a ``typed'', neither, or both. Three class attributes of
1549 \class{Option
} (or your
\class{Option
} subclass) control this:
1551 \begin{memberdesc
}{ACTIONS
}
1552 All actions must be listed as strings in ACTIONS.
1554 \begin{memberdesc
}{STORE_ACTIONS
}
1555 "store" actions are additionally listed here.
1557 \begin{memberdesc
}{TYPED_ACTIONS
}
1558 "typed" actions are additionally listed here.
1561 In order to actually implement your new action, you must override
1562 \class{Option
}'s
\method{take_action()
} method and add a case that
1563 recognizes your action.
1565 For example, let's add an ``extend'' action. This is similar to the
1566 standard ``append'' action, but instead of taking a single value from
1567 the command-line and appending it to an existing list, ``extend'' will
1568 take multiple values in a single comma-delimited string, and extend an
1569 existing list with them. That is, if
\longprogramopt{names
} is an
1570 ``extend'' option of type string, the command line:
1573 --names=foo,bar --names blah --names ding,dong
1576 would result in a list:
1579 ["foo", "bar", "blah", "ding", "dong"
]
1582 Again we define a subclass of
\class{Option
}:
1585 class MyOption (Option):
1587 ACTIONS = Option.ACTIONS + ("extend",)
1588 STORE_ACTIONS = Option.STORE_ACTIONS + ("extend",)
1589 TYPED_ACTIONS = Option.TYPED_ACTIONS + ("extend",)
1591 def take_action (self, action, dest, opt, value, values, parser):
1592 if action == "extend":
1593 lvalue = value.split(",")
1594 values.ensure_value(dest,
[]).extend(lvalue)
1597 self, action, dest, opt, value, values, parser)
1603 \item ``extend'' both expects a value on the command-line and stores that
1604 value somewhere, so it goes in both
\member{STORE_ACTIONS
} and
1605 \member{TYPED_ACTIONS
}.
1607 \item \method{MyOption.take_action()
} implements just this one new
1608 action, and passes control back to
\method{Option.take_action()
} for
1609 the standard
\module{optparse
} actions.
1611 \item \var{values
} is an instance of the
\class{Values
} class, which
1612 provides the very useful
\method{ensure_value()
}
1613 method.
\method{ensure_value()
} is essentially
\function{getattr()
}
1614 with a safety valve; it is called as:
1617 values.ensure_value(attr, value)
1621 If the
\member{attr
} attribute of
\var{values
} doesn't exist or is
1622 None, then
\method{ensure_value()
} first sets it to
\var{value
}, and
1623 then returns
\var{value
}. This is very handy for actions like
1624 ``extend'', ``append'', and ``count'', all of which accumulate data in
1625 a variable and expect that variable to be of a certain type (a list
1626 for the first two, an integer for the latter). Using
1627 \method{ensure_value()
} means that scripts using your action don't
1628 have to worry about setting a default value for the option
1629 destinations in question; they can just leave the default as None and
1630 \method{ensure_value()
} will take care of getting it right when it's
1633 \subsubsection{Other reasons to extend
\module{optparse
}\label{optparse-extending-other-reasons
}}
1635 Adding new types and new actions are the big, obvious reasons why you
1636 might want to extend
\module{optparse
}. I can think of at least two
1637 other areas to play with.
1639 First, the simple one:
\class{OptionParser
} tries to be helpful by
1640 calling
\function{sys.exit()
} when appropriate, ie. when there's an
1641 error on the command-line or when the user requests help. In the
1642 former case, the traditional course of letting the script crash with a
1643 traceback is unacceptable; it will make users think there's a bug in
1644 your script when they make a command-line error. In the latter case,
1645 there's generally not much point in carrying on after printing a help
1648 If this behaviour bothers you, it shouldn't be too hard to ``fix'' it.
1652 \item subclass OptionParser and override the error() method
1653 \item subclass Option and override the take_action() method -- you'll
1654 need to provide your own handling of the "help" action that
1655 doesn't call sys.exit()
1658 The second, much more complex, possibility is to override the
1659 command-line syntax implemented by
\module{optparse
}. In this case,
1660 you'd leave the whole machinery of option actions and types alone, but
1661 rewrite the code that processes
\var{sys.argv
}. You'll need to
1662 subclass
\class{OptionParser
} in any case; depending on how radical a
1663 rewrite you want, you'll probably need to override one or all of
1664 \method{parse_args()
},
\method{_process_long_opt()
}, and
1665 \method{_process_short_opts()
}.
1667 Both of these are left as an exercise for the reader. I have not
1668 tried to implement either myself, since I'm quite happy with
1669 \module{optparse
}'s default behaviour (naturally).
1671 Happy hacking, and don't forget: Use the Source, Luke.
1673 \subsubsection{Examples
\label{optparse-extending-examples
}}
1675 Here are a few examples of extending the
\module{optparse
} module.
1677 First, let's change the option-parsing to be case-insensitive:
1679 \verbatiminput{caseless.py
}
1681 And two ways of implementing ``required options'' with
1684 Version
1: Add a method to
\class{OptionParser
} which applications
1685 must call after parsing arguments:
1687 \verbatiminput{required_1.py
}
1689 Version
2: Extend
\class{Option
} and add a
\member{required
}
1690 attribute; extend
\class{OptionParser
} to ensure that required options
1691 are present after parsing:
1693 \verbatiminput{required_2.py
}