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=True,
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 == False
}, 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{Philosophy
\label{optparse-philosophy
}}
70 The purpose of
\module{optparse
} is to make it very easy to provide the
71 most standard, obvious, straightforward, and user-friendly user
72 interface for
\UNIX{} command-line programs. The
\module{optparse
}
73 philosophy is heavily influenced by the
\UNIX{} and GNU toolkits, and
74 this section is meant to explain that philosophy.
76 \subsubsection{Terminology
\label{optparse-terminology
}}
78 First, we need to establish some terminology.
82 a chunk of text that a user enters on the command-line, and that the
83 shell passes to
\cfunction{execl()
} or
\cfunction{execv()
}. In
84 Python, arguments are elements of
85 \code{sys.argv
[1:
]}. (
\code{sys.argv
[0]} is the name of the program
86 being executed; in the context of parsing arguments, it's not very
87 important.)
\UNIX{} shells also use the term ``word''.
89 It is occasionally desirable to use an argument list other than
90 \code{sys.argv
[1:
]}, so you should read ``argument'' as ``an element of
91 \code{sys.argv
[1:
]}, or of some other list provided as a substitute for
92 \code{sys.argv
[1:
]}''.
95 an argument used to supply extra information to guide or customize
96 the execution of a program. There are many different syntaxes for
97 options; the traditional
\UNIX{} syntax is
\programopt{-
} followed by a
98 single letter, e.g.
\programopt{-x
} or
\programopt{-F
}. Also,
99 traditional
\UNIX{} syntax allows multiple options to be merged into a
100 single argument, e.g.
\programopt{-x -F
} is equivalent to
101 \programopt{-xF
}. The GNU project introduced
\longprogramopt{}
102 followed by a series of hyphen-separated words,
103 e.g.
\longprogramopt{file
} or
\longprogramopt{dry-run
}. These are
104 the only two option syntaxes provided by
\module{optparse
}.
106 Some other option syntaxes that the world has seen include:
109 \item a hyphen followed by a few letters, e.g.
\programopt{-pf
} (this is
110 \emph{not
} the same as multiple options merged into a single
112 \item a hyphen followed by a whole word, e.g.
\programopt{-file
} (this is
113 technically equivalent to the previous syntax, but they aren't
114 usually seen in the same program.)
115 \item a plus sign followed by a single letter, or a few letters,
116 or a word, e.g.
\programopt{+f
},
\programopt{+rgb
}.
117 \item a slash followed by a letter, or a few letters, or a word, e.g.
118 \programopt{/f
},
\programopt{/file
}.
121 \module{optparse
} does not support these option syntaxes, and it never
122 will. (If you really want to use one of those option syntaxes, you'll
123 have to subclass
\class{OptionParser
} and override all the difficult
124 bits. But please don't!
\module{optparse
} does things the traditional
125 \UNIX/GNU way deliberately; the first three are non-standard anywhere,
126 and the last one makes sense only if you're exclusively targeting
127 MS-DOS/Windows and/or VMS.)
129 \term{option argument
}
130 an argument that follows an option, is closely associated with that
131 option, and is consumed from the argument list when the option is.
132 Often, option arguments may also be included in the same argument as
139 may be equivalent to:
145 (
\module{optparse
} supports this syntax.)
147 Some options never take an argument. Some options always take an
148 argument. Lots of people want an ``optional option arguments'' feature,
149 meaning that some options will take an argument if they see it, and
150 won't if they don't. This is somewhat controversial, because it makes
151 parsing ambiguous: if
\programopt{-a
} and
\programopt{-b
} are both
152 options, and
\programopt{-a
} takes an optional argument, how do we
153 interpret
\programopt{-ab
}?
\module{optparse
} does not support optional
156 \term{positional argument
}
157 something leftover in the argument list after options have been
158 parsed, i.e., after options and their arguments have been parsed and
159 removed from the argument list.
161 \term{required option
}
162 an option that must be supplied on the command-line. The phrase
163 ``required option'' is an oxymoron; the presence of ``required options''
164 in a program is usually a sign of careless user interface design.
165 \module{optparse
} doesn't prevent you from implementing required
166 options, but doesn't give you much help with it either. See ``Extending
167 Examples'' (section~
\ref{optparse-extending-examples
}) for two ways to
168 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 \code{/tmp/
report.txt
} is an option argument.
\code{foo
} and
\code{bar
}
181 are 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 should be
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
\program{find
},
\program{tar
},
191 and
\program{dd
}---all of which are mutant oddballs that have been
192 rightly criticized for their non-standard syntax and confusing
195 Lots of people want their programs to have ``required options''.
196 Think about it. If it's required, then it's
\emph{not optional
}! If
197 there is a piece of information that your program absolutely requires
198 in order to run successfully, that's what positional arguments are
199 for. (However, if you insist on adding ``required options'' to your
200 programs, look in ``Extending Examples''
201 (section~
\ref{optparse-extending-examples
}) for two ways of
202 implementing them with
\module{optparse
}.)
204 Consider the humble
\program{cp
} utility, for copying files. It
205 doesn't make much sense to try to copy files without supplying a
206 destination and at least one source. Hence,
\program{cp
} fails if you
207 run it with no arguments. However, it has a flexible, useful syntax
208 that does not rely on options at all:
212 $ cp SOURCE ... DEST-DIR
215 You can get pretty far with just that. Most
\program{cp
}
216 implementations provide a bunch of options to tweak exactly how the
217 files are copied: you can preserve mode and modification time, avoid
218 following symlinks, ask before clobbering existing files, etc. But
219 none of this distracts from the core mission of
\program{cp
}, which is
220 to copy one file to another, or N files to another directory.
222 \subsubsection{What are positional arguments for?
\label{optparse-positional-arguments
}}
224 In case it wasn't clear from the above example: positional arguments
225 are for those pieces of information that your program absolutely,
226 positively requires to run.
228 A good user interface should have as few absolute requirements as
229 possible. If your program requires
17 distinct pieces of information in
230 order to run successfully, it doesn't much matter
\emph{how
} you get that
231 information from the user---most people will give up and walk away
232 before they successfully run the program. This applies whether the user
233 interface is a command-line, a configuration file, a GUI, or whatever:
234 if you make that many demands on your users, most of them will just give
237 In short, try to minimize the amount of information that users are
238 absolutely required to supply---use sensible defaults whenever
239 possible. Of course, you also want to make your programs reasonably
240 flexible. That's what options are for. Again, it doesn't matter if
241 they are entries in a config file, checkboxes in the ``Preferences''
242 dialog of a GUI, or command-line options---the more options you
243 implement, the more flexible your program is, and the more complicated
244 its implementation becomes. It's quite easy to overwhelm users (and
245 yourself!) with too much flexibility, so be careful there.
247 \subsection{Basic Usage
\label{optparse-basic-usage
}}
249 While
\module{optparse
} is quite flexible and powerful, you don't have
250 to jump through hoops or read reams of documentation to get it working
251 in basic cases. This
document aims to demonstrate some simple usage
252 patterns that will get you started using
\module{optparse
} in your
255 To parse a command line with
\module{optparse
}, you must create an
256 \class{OptionParser
} instance and populate it. Obviously, you'll have
257 to import the
\class{OptionParser
} classes in any script that uses
261 from optparse import OptionParser
264 Early on in the main program, create a parser:
267 parser = OptionParser()
270 Then you can start populating the parser with options. Each option is
271 really a set of synonymous option strings; most commonly, you'll have
272 one short option string and one long option string ---
273 e.g.
\programopt{-f
} and
\longprogramopt{file
}:
276 parser.add_option("-f", "--file", ...)
279 The interesting stuff, of course, is what comes after the option
280 strings. For now, we'll only cover four of the things you can put
281 there:
\emph{action
},
\emph{type
},
\emph{dest
} (destination), and
284 \subsubsection{The
\emph{store
} action
%
285 \label{optparse-store-action
}}
287 The action tells
\module{optparse
} what to do when it sees one of the
288 option strings for this option on the command-line. For example, the
289 action
\emph{store
} means: take the next argument (or the remainder of
290 the current argument), ensure that it is of the correct type, and
291 store it to your chosen destination.
293 For example, let's fill in the ``...'' of that last option:
296 parser.add_option("-f", "--file",
297 action="store", type="string", dest="filename")
300 Now let's make up a fake command-line and ask
\module{optparse
} to
304 args =
["-f", "foo.txt"
]
305 (options, args) = parser.parse_args(args)
308 (Note that if you don't pass an argument list to
309 \function{parse_args()
}, it automatically uses
\code{sys.argv
[1:
]}.)
311 When
\module{optparse
} sees the
\programopt{-f
}, it consumes the next
312 argument---
\code{foo.txt
}---and stores it in the
\member{filename
}
313 attribute of a special object. That object is the first return value
314 from
\function{parse_args()
}, so:
317 print options.filename
320 will print
\code{foo.txt
}.
322 Other option types supported by
\module{optparse
} are
\code{int
} and
323 \code{float
}. Here's an option that expects an integer argument:
326 parser.add_option("-n", type="int", dest="num")
329 This example doesn't provide a long option, which is perfectly
330 acceptable. It also doesn't specify the action---it defaults to
333 Let's parse another fake command-line. This time, we'll jam the option
334 argument right up against the option, since
\programopt{-n42
} (one
335 argument) is equivalent to
\programopt{-n
42} (two arguments).
338 (options, args) = parser.parse_args(
["-n42"
])
342 This prints
\code{42}.
344 Trying out the ``float'' type is left as an exercise for the reader.
346 If you don't specify a type,
\module{optparse
} assumes ``string''.
347 Combined with the fact that the default action is ``store'', that
348 means our first example can be a lot shorter:
351 parser.add_option("-f", "--file", dest="filename")
354 If you don't supply a destination,
\module{optparse
} figures out a
355 sensible default from the option strings: if the first long option
356 string is
\longprogramopt{foo-bar
}, then the default destination is
357 \member{foo_bar
}. If there are no long option strings,
358 \module{optparse
} looks at the first short option: the default
359 destination for
\programopt{-f
} is
\member{f
}.
361 Adding types is fairly easy; please refer to
362 section~
\ref{optparse-adding-types
}, ``Adding new types.''
364 \subsubsection{Other
\emph{store_*
} actions
%
365 \label{optparse-other-store-actions
}}
367 Flag options---set a variable to true or false when a particular
368 option is seen---are quite common.
\module{optparse
} supports them
369 with two separate actions, ``store_true'' and ``store_false''. For
370 example, you might have a
\var{verbose
} flag that is turned on with
371 \programopt{-v
} and off with
\programopt{-q
}:
374 parser.add_option("-v", action="store_true", dest="verbose")
375 parser.add_option("-q", action="store_false", dest="verbose")
378 Here we have two different options with the same destination, which is
379 perfectly OK. (It just means you have to be a bit careful when setting
380 default values---see below.)
382 When
\module{optparse
} sees
\programopt{-v
} on the command line, it sets
383 \code{options.verbose
} to
\code{True
}; when it sees
\programopt{-q
}, it
384 sets
\code{options.verbose
} to
\code{False
}.
386 \subsubsection{Setting default values
\label{optparse-setting-default-values
}}
388 All of the above examples involve setting some variable (the
389 ``destination'') when certain command-line options are seen. What
390 happens if those options are never seen? Since we didn't supply any
391 defaults, they are all set to
\code{None
}. Sometimes, this is just fine (which
392 is why it's the default), but sometimes, you want more control. To
393 address that need,
\module{optparse
} lets you supply a default value for
394 each destination, which is assigned before the command-line is parsed.
396 First, consider the verbose/quiet example. If we want
397 \module{optparse
} to set
\member{verbose
} to
\code{True
} unless
398 \programopt{-q
} is seen, then we can do this:
401 parser.add_option("-v", action="store_true", dest="verbose", default=True)
402 parser.add_option("-q", action="store_false", dest="verbose")
405 Oddly enough, this is exactly equivalent:
408 parser.add_option("-v", action="store_true", dest="verbose")
409 parser.add_option("-q", action="store_false", dest="verbose", default=True)
412 Those are equivalent because you're supplying a default value for the
413 option's
\emph{destination
}, and these two options happen to have the same
414 destination (the
\member{verbose
} variable).
419 parser.add_option("-v", action="store_true", dest="verbose", default=False)
420 parser.add_option("-q", action="store_false", dest="verbose", default=True)
423 Again, the default value for
\member{verbose
} will be
\code{True
}: the last
424 default value supplied for any particular destination is the one that
427 \subsubsection{Generating help
\label{optparse-generating-help
}}
429 The last feature that you will use in every script is
430 \module{optparse
}'s ability to generate help messages. All you have
431 to do is supply a
\var{help
} argument when you add an option. Let's
432 create a new parser and populate it with user-friendly (documented)
436 usage = "usage:
%prog [options] arg1 arg2"
437 parser = OptionParser(usage=usage)
438 parser.add_option("-v", "--verbose",
439 action="store_true", dest="verbose", default=True,
440 help="make lots of noise
[default
]")
441 parser.add_option("-q", "--quiet",
442 action="store_false", dest="verbose",
443 help="be vewwy quiet (I'm hunting wabbits)")
444 parser.add_option("-f", "--file", dest="filename",
445 metavar="FILE", help="write output to FILE"),
446 parser.add_option("-m", "--mode",
447 default="intermediate",
448 help="interaction mode: one of 'novice', "
449 "'intermediate'
[default
], 'expert'")
452 If
\module{optparse
} encounters either
\programopt{-h
} or
453 \longprogramopt{help
} on the command-line, or if you just call
454 \method{parser.print_help()
}, it prints the following to stdout:
457 usage: <yourscript>
[options
] arg1 arg2
460 -h, --help show this help message and exit
461 -v, --verbose make lots of noise
[default
]
462 -q, --quiet be vewwy quiet (I'm hunting wabbits)
463 -fFILE, --file=FILE write output to FILE
464 -mMODE, --mode=MODE interaction mode: one of 'novice', 'intermediate'
468 There's a lot going on here to help
\module{optparse
} generate the
469 best possible help message:
472 \item the script defines its own usage message:
475 usage = "usage:
%prog [options] arg1 arg2"
478 \module{optparse
} expands
\samp{\%prog
} in the usage string to the name of the
479 current script, i.e.
\code{os.path.basename(sys.argv
[0])
}. The
480 expanded string is then printed before the detailed option help.
482 If you don't supply a usage string,
\module{optparse
} uses a bland but
483 sensible default:
\code{"usage: \%prog
[options
]"
}, which is fine if your
484 script doesn't take any positional arguments.
486 \item every option defines a help string, and doesn't worry about
487 line-wrapping---
\module{optparse
} takes care of wrapping lines and
488 making the help output look good.
490 \item options that take a value indicate this fact in their
491 automatically-generated help message, e.g. for the ``mode'' option:
497 Here, ``MODE'' is called the meta-variable: it stands for the argument
498 that the user is expected to supply to
499 \programopt{-m
}/
\longprogramopt{mode
}. By default,
\module{optparse
}
500 converts the destination variable name to uppercase and uses that for
501 the meta-variable. Sometimes, that's not what you want---for
502 example, the
\var{filename
} option explicitly sets
503 \code{metavar="FILE"
}, resulting in this automatically-generated
510 This is important for more than just saving space, though: the
511 manually written help text uses the meta-variable ``FILE'', to clue
512 the user in that there's a connection between the formal syntax
513 ``-fFILE'' and the informal semantic description ``write output to
514 FILE''. This is a simple but effective way to make your help text a
515 lot clearer and more useful for end users.
518 When dealing with many options, it is convenient to group these
519 options for better help output. An
\class{OptionParser
} can contain
520 several option groups, each of which can contain several options.
522 Continuing with the parser defined above, adding an
523 \class{OptionGroup
} to a parser is easy:
526 group = OptionGroup(parser, "Dangerous Options",
527 "Caution: use these options at your own risk. "
528 "It is believed that some of them bite.")
529 group.add_option("-g", action="store_true", help="Group option.")
530 parser.add_option_group(group)
533 This would result in the following help output:
536 usage:
[options
] arg1 arg2
539 -h, --help show this help message and exit
540 -v, --verbose make lots of noise
[default
]
541 -q, --quiet be vewwy quiet (I'm hunting wabbits)
542 -fFILE, --file=FILE write output to FILE
543 -mMODE, --mode=MODE interaction mode: one of 'novice', 'intermediate'
547 Caution: use of these options is at your own risk. It is believed that
553 \subsubsection{Print a version number
\label{optparse-print-version
}}
555 Similar to the brief usage string,
\module{optparse
} can also print a
556 version string for your program. You have to supply the string, as
557 the
\var{version
} argument to
\class{OptionParser
}:
560 parser = OptionParser(usage="
%prog [-f] [-q]", version="%prog 1.0")
563 \var{version
} can contain anything you like;
\code{\%prog
} is expanded
564 in
\var{version
} just as with
\var{usage
}. When you supply it,
565 \module{optparse
} automatically adds a
\longprogramopt{version
} option
566 to your parser. If it encounters this option on the command line, it
567 expands your
\var{version
} string (by replacing
\code{\%prog
}), prints
568 it to stdout, and exits.
570 For example, if your script is called /usr/bin/foo, a user might do:
573 $ /usr/bin/foo --version
575 \end{verbatim
} % $ (avoid confusing emacs)
577 \subsubsection{Error-handling
\label{optparse-error-handling
}}
579 The one thing you need to know for basic usage is how
580 \module{optparse
} behaves when it encounters an error on the
581 command-line---e.g.
\programopt{-n
4x
} where
\programopt{-n
} is an
582 integer-valued option. In this case,
\module{optparse
} prints your
583 usage message to stderr, followed by a useful and human-readable error
584 message. Then it terminates (calls
\function{sys.exit()
}) with a
585 non-zero exit status.
587 If you don't like this, subclass
\class{OptionParser
} and override the
588 \method{error()
} method. See section~
\ref{optparse-extending
},
589 ``Extending
\module{optparse
}.''
591 \subsubsection{Putting it all together
\label{optparse-basic-summary
}}
593 Here's what
\module{optparse
}-based scripts typically look like:
596 from optparse import OptionParser
599 usage = "usage: \%prog
[-f
] [-v
] [-q
] firstarg secondarg"
600 parser = OptionParser(usage)
601 parser.add_option("-f", "--file", type="string", dest="filename",
602 help="read data from FILENAME")
603 parser.add_option("-v", "--verbose",
604 action="store_true", dest="verbose")
605 parser.add_option("-q", "--quiet",
606 action="store_false", dest="verbose")
608 (options, args) = parser.parse_args()
610 parser.error("incorrect number of arguments")
613 print "reading \%s..." \% options.filename
616 if __name__ == "__main__":
620 \subsection{Advanced Usage
\label{optparse-advanced-usage
}}
622 \subsubsection{Creating and populating the
623 parser
\label{optparse-creating-the-parser
}}
625 There are several ways to populate the parser with options. One way
626 is to pass a list of
\class{Options
} to the
\class{OptionParser
}
630 from optparse import OptionParser, make_option
632 parser = OptionParser(option_list=
[
633 make_option("-f", "--filename",
634 action="store", type="string", dest="filename"),
635 make_option("-q", "--quiet",
636 action="store_false", dest="verbose")
])
639 (
\function{make_option()
} is a factory function for generating
640 \class{Option
} objects.)
642 For long option lists, it may be more convenient/readable to create the
646 option_list =
[make_option("-f", "--filename",
647 action="store", type="string", dest="filename"),
648 [... more options ...
]
649 make_option("-q", "--quiet",
650 action="store_false", dest="verbose")
]
651 parser = OptionParser(option_list=option_list)
654 Or, you can use the
\method{add_option()
} method of
655 \class{OptionParser
} to add options one-at-a-time:
658 parser = OptionParser()
659 parser.add_option("-f", "--filename",
660 action="store", type="string", dest="filename")
661 parser.add_option("-q", "--quiet",
662 action="store_false", dest="verbose")
665 This method makes it easier to track down exceptions raised by the
666 \class{Option
} constructor, which are common because of the complicated
667 interdependencies among the various keyword arguments. (If you get it
668 wrong,
\module{optparse
} raises
\exception{OptionError
}.)
670 \method{add_option()
} can be called in one of two ways:
673 \item pass it an
\class{Option
} instance (as returned by
\function{make_option()
})
674 \item pass it any combination of positional and keyword arguments that
675 are acceptable to
\function{make_option()
} (i.e., to the
\class{Option
}
676 constructor), and it will create the
\class{Option
} instance for you
680 \subsubsection{Defining options
\label{optparse-defining-options
}}
682 Each
\class{Option
} instance represents a set of synonymous
683 command-line options, i.e. options that have the same meaning and
684 effect, but different spellings. You can specify any number of short
685 or long option strings, but you must specify at least one option
688 To define an option with only a short option string:
691 make_option("-f", ...)
694 And to define an option with only a long option string:
697 make_option("--foo", ...)
700 The ``...'' represents a set of keyword arguments that define attributes
701 of the
\class{Option
} object. The rules governing which keyword args
702 you must supply for a given
\class{Option
} are fairly complicated, but
703 you always have to supply
\emph{some
}. If you get it wrong,
704 \module{optparse
} raises an
\exception{OptionError
} exception explaining
707 The most important attribute of an option is its action, i.e. what to do
708 when we encounter this option on the command-line. The possible actions
711 \begin{tableii
}{l|l
}{code
}{Action
}{Meaning
}
712 \lineii{store
}{store this option's argument (default)
}
713 \lineii{store_const
}{store a constant value
}
714 \lineii{store_true
}{store a true value
}
715 \lineii{store_false
}{store a false value
}
716 \lineii{append
}{append this option's argument to a list
}
717 \lineii{count
}{increment a counter by one
}
718 \lineii{callback
}{call a specified function
}
719 \lineii{help
}{print a usage message including all options and the
720 documentation for them
}
723 (If you don't supply an action, the default is ``store''. For this
724 action, you may also supply
\var{type
} and
\var{dest
} keywords; see
727 As you can see, most actions involve storing or updating a value
728 somewhere.
\module{optparse
} always creates a particular object (an
729 instance of the
\class{Values
} class) specifically for this
730 purpose. Option arguments (and various other values) are stored as
731 attributes of this object, according to the
\var{dest
} (destination)
732 argument to
\function{make_option()
}/
\method{add_option()
}.
734 For example, when you call:
740 one of the first things
\module{optparse
} does is create a
741 \code{values
} object:
747 If one of the options in this parser is defined with:
750 make_option("-f", "--file", action="store", type="string", dest="filename")
753 and the command-line being parsed includes any of the following:
762 then
\module{optparse
}, on seeing the
\programopt{-f
} or
763 \longprogramopt{file
} option, will do the equivalent of this:
766 values.filename = "foo"
769 Clearly, the
\var{type
} and
\var{dest
} arguments are almost
770 as important as
\var{action
}.
\var{action
} is the only attribute that
771 is meaningful for
\emph{all
} options, though, so it is the most
774 \subsubsection{Option actions
\label{optparse-option-actions
}}
776 The various option actions all have slightly different requirements
777 and effects. Except for the ``help'' action, you must supply at least
778 one other keyword argument when creating the
\class{Option
}; the exact
779 requirements for each action are listed here.
782 \term{store
} [relevant:
\var{type
},
\var{dest
},
\var{nargs
},
\var{choices
}]
784 The option must be followed by an argument, which is converted to a
785 value according to
\var{type
} and stored in
\var{dest
}. If
786 \code{nargs >
1}, multiple arguments will be consumed from the command
787 line; all will be converted according to
\var{type
} and stored to
788 \var{dest
} as a tuple. See section~
\ref{optparse-option-types
},
789 ``Option types,'' below.
791 If
\var{choices
} (a sequence of strings) is supplied, the type
792 defaults to ``choice''.
794 If
\var{type
} is not supplied, it defaults to ``string''.
796 If
\var{dest
} is not supplied,
\module{optparse
} derives a
797 destination from the first long option strings (e.g.,
798 \longprogramopt{foo-bar
} becomes
\member{foo_bar
}). If there are no long
799 option strings,
\module{optparse
} derives a destination from the first
800 short option string (e.g.,
\programopt{-f
} becomes
\member{f
}).
806 make_option("-p", type="float", nargs=
3, dest="point")
809 Given the following command line:
812 -f foo.txt -p
1 -
3.5 4 -fbar.txt
815 \module{optparse
} will set:
819 values.point = (
1.0, -
3.5,
4.0)
822 (Actually,
\member{values.f
} will be set twice, but only the second
823 time is visible in the end.)
825 \term{store_const
} [required:
\var{const
},
\var{dest
}]
827 The
\var{const
} value supplied to the
\class{Option
} constructor is
828 stored in
\var{dest
}.
833 make_option("-q", "--quiet",
834 action="store_const", const=
0, dest="verbose"),
835 make_option("-v", "--verbose",
836 action="store_const", const=
1, dest="verbose"),
837 make_option("--noisy",
838 action="store_const", const=
2, dest="verbose"),
841 If
\longprogramopt{noisy
} is seen,
\module{optparse
} will set:
847 \term{store_true
} [required:
\var{dest
}]
849 A special case of ``store_const'' that stores
\code{True
} to
\var{dest
}.
851 \term{store_false
} [required:
\var{dest
}]
853 Like ``store_true'', but stores
\code{False
}
858 make_option(None, "--clobber", action="store_true", dest="clobber")
859 make_option(None, "--no-clobber", action="store_false", dest="clobber")
862 \term{append
} [relevant:
\var{type
},
\var{dest
},
\var{nargs
},
\var{choices
}]
864 The option must be followed by an argument, which is appended to the
865 list in
\var{dest
}. If no default value for
\var{dest
} is supplied
866 (i.e. the default is
\code{None
}), an empty list is automatically created when
867 \module{optparse
} first encounters this option on the command-line.
868 If
\code{nargs >
1}, multiple arguments are consumed, and a tuple of
869 length
\var{nargs
} is appended to
\var{dest
}.
871 The defaults for
\var{type
} and
\var{dest
} are the same as for the
877 make_option("-t", "--tracks", action="append", type="int")
880 If
\programopt{-t3
} is seen on the command-line,
\module{optparse
} does the equivalent of:
884 values.tracks.append(int("
3"))
887 If, a little later on,
\longprogramopt{tracks=
4} is seen, it does:
890 values.tracks.append(int("
4"))
893 See ``Error handling'' (section~
\ref{optparse-error-handling
}) for
894 information on how
\module{optparse
} deals with something like
895 \longprogramopt{tracks=x
}.
897 \term{count
} [required:
\var{dest
}]
899 Increment the integer stored at
\var{dest
}.
\var{dest
} is set to zero
900 before being incremented the first time (unless you supply a default
906 make_option("-v", action="count", dest="verbosity")
909 The first time
\programopt{-v
} is seen on the command line,
910 \module{optparse
} does the equivalent of:
914 values.verbosity +=
1
917 Every subsequent occurrence of
\programopt{-v
} results in:
920 values.verbosity +=
1
923 \term{callback
} [required:
\var{callback
};
924 relevant:
\var{type
},
\var{nargs
},
\var{callback_args
},
925 \var{callback_kwargs
}]
927 Call the function specified by
\var{callback
}. The signature of
928 this function should be:
931 func(option : Option,
934 parser : OptionParser,
938 Callback options are covered in detail in
939 section~
\ref{optparse-callback-options
}, ``Callback Options.''
941 \term{help
} [required: none
]
943 Prints a complete help message for all the options in the current
944 option parser. The help message is constructed from the
\var{usage
}
945 string passed to
\class{OptionParser
}'s constructor and the
\var{help
}
946 string passed to every option.
948 If no
\var{help
} string is supplied for an option, it will still be
949 listed in the help message. To omit an option entirely, use the
950 special value
\constant{optparse.SUPPRESS_HELP
}.
955 from optparse import Option, OptionParser, SUPPRESS_HELP
957 usage = "usage:
%prog [options]"
958 parser = OptionParser(usage, option_list=
[
959 make_option("-h", "--help", action="help"),
960 make_option("-v", action="store_true", dest="verbose",
961 help="Be moderately verbose")
962 make_option("--file", dest="filename",
963 help="Input file to read data from"),
964 make_option("--secret", help=SUPPRESS_HELP)
968 If
\module{optparse
} sees either
\programopt{-h
} or
969 \longprogramopt{help
} on the command line, it will print something
970 like the following help message to stdout:
973 usage: <yourscript>
[options
]
976 -h, --help Show this help message and exit
977 -v Be moderately verbose
978 --file=FILENAME Input file to read data from
981 After printing the help message,
\module{optparse
} terminates your process
982 with
\code{sys.exit(
0)
}.
984 \term{version
} [required: none
]
986 Prints the version number supplied to the
\class{OptionParser
} to
987 stdout and exits. The version number is actually formatted and
988 printed by the
\method{print_version()
} method of
989 \class{OptionParser
}. Generally only relevant if the
\var{version
}
990 argument is supplied to the
\class{OptionParser
} constructor.
993 \subsubsection{Option types
\label{optparse-option-types
}}
995 \module{optparse
} supports six option types out of the box:
\dfn{string
},
996 \dfn{int
},
\dfn{long
},
\dfn{choice
},
\dfn{float
} and
\dfn{complex
}.
997 (Of these, string, int, float, and choice are the most commonly used
998 ---long and complex are there mainly for completeness.) It's easy to
999 add new option types by subclassing the
\class{Option
} class; see
1000 section~
\ref{optparse-extending
}, ``Extending
\module{optparse
}.''
1002 Arguments to string options are not checked or converted in any way:
1003 the text on the command line is stored in the destination (or passed
1004 to the callback) as-is.
1006 Integer arguments are passed to
\function{int()
} to convert them to
1007 Python integers. If
\function{int()
} fails, so will
1008 \module{optparse
}, although with a more useful error message.
1009 Internally,
\module{optparse
} raises
\exception{OptionValueError
} in
1010 \function{optparse.check_builtin()
}; at a higher level (in
1011 \class{OptionParser
}),
\module{optparse
} catches this exception and
1012 terminates your program with a useful error message.
1014 Likewise, float arguments are passed to
\function{float()
} for
1015 conversion, long arguments to
\function{long()
}, and complex arguments
1016 to
\function{complex()
}. Apart from that, they are handled
1017 identically to integer arguments.
1019 Choice options are a subtype of string options. A master list or
1020 tuple of choices (strings) must be passed to the option constructor
1021 (
\function{make_option()
} or
\method{OptionParser.add_option()
}) as
1022 the
\var{choices
} keyword argument. Choice option arguments are
1023 compared against this master list in
1024 \function{optparse.check_choice()
}, and
\exception{OptionValueError
}
1025 is raised if an unknown string is given.
1027 \subsubsection{Querying and manipulating your option parser
\label{optparse-querying-and-manipulating
}}
1029 Sometimes, it's useful to poke around your option parser and see what's
1030 there.
\class{OptionParser
} provides a couple of methods to help you out:
1032 \begin{methoddesc
}{has_option
}{opt_str
}
1033 Given an option string such as
\programopt{-q
} or
1034 \longprogramopt{verbose
}, returns true if the
\class{OptionParser
}
1035 has an option with that option string.
1038 \begin{methoddesc
}{get_option
}{opt_str
}
1039 Returns the
\class{Option
} instance that implements the option
1040 string you supplied, or
\code{None
} if no options implement it.
1043 \begin{methoddesc
}{remove_option
}{opt_str
}
1044 If the
\class{OptionParser
} has an option corresponding to
1045 \var{opt_str
}, that option is removed. If that option provided
1046 any other option strings, all of those option strings become
1049 If
\var{opt_str
} does not occur in any option belonging to this
1050 \class{OptionParser
}, raises
\exception{ValueError
}.
1053 \subsubsection{Conflicts between options
\label{optparse-conflicts
}}
1055 If you're not careful, it's easy to define conflicting options:
1058 parser.add_option("-n", "--dry-run", ...)
1060 parser.add_option("-n", "--noisy", ...)
1063 (This is even easier to do if you've defined your own
1064 \class{OptionParser
} subclass with some standard options.)
1066 On the assumption that this is usually a mistake,
\module{optparse
}
1067 raises an exception (
\exception{OptionConflictError
}) by default when
1068 this happens. Since this is an easily-fixed programming error, you
1069 shouldn't try to catch this exception---fix your mistake and get on
1072 Sometimes, you want newer options to deliberately replace the option
1073 strings used by older options. You can achieve this by calling:
1076 parser.set_conflict_handler("resolve")
1079 which instructs
\module{optparse
} to resolve option conflicts
1082 Here's how it works: every time you add an option,
\module{optparse
}
1083 checks for conflicts with previously-added options. If it finds any,
1084 it invokes the conflict-handling mechanism you specify either to the
1085 \class{OptionParser
} constructor:
1088 parser = OptionParser(..., conflict_handler="resolve")
1091 or via the
\method{set_conflict_handler()
} method.
1093 The default conflict-handling mechanism is
\code{error
}.
1095 Here's an example: first, define an
\class{OptionParser
} set to
1096 resolve conflicts intelligently:
1099 parser = OptionParser(conflict_handler="resolve")
1102 Now add all of our options:
1105 parser.add_option("-n", "--dry-run", ..., help="original dry-run option")
1107 parser.add_option("-n", "--noisy", ..., help="be noisy")
1110 At this point,
\module{optparse
} detects that a previously-added option is already
1111 using the
\programopt{-n
} option string. Since
\code{conflict_handler
1112 == "resolve"
}, it resolves the situation by removing
\programopt{-n
}
1113 from the earlier option's list of option strings. Now,
1114 \longprogramopt{dry-run
} is the only way for the user to activate that
1115 option. If the user asks for help, the help message will reflect
1120 --dry-run original dry-run option
1122 -n, --noisy be noisy
1125 Note that it's possible to whittle away the option strings for a
1126 previously-added option until there are none left, and the user has no
1127 way of invoking that option from the command-line. In that case,
1128 \module{optparse
} removes that option completely, so it doesn't show
1129 up in help text or anywhere else. E.g. if we carry on with our
1130 existing
\class{OptionParser
}:
1133 parser.add_option("--dry-run", ..., help="new dry-run option")
1136 At this point, the first
\programopt{-n
}/
\longprogramopt{dry-run
}
1137 option is no longer accessible, so
\module{optparse
} removes it. If
1138 the user asks for help, they'll get something like this:
1143 -n, --noisy be noisy
1144 --dry-run new dry-run option
1147 \subsection{Callback Options
\label{optparse-callback-options
}}
1149 If
\module{optparse
}'s built-in actions and types just don't fit the
1150 bill for you, but it's not worth extending
\module{optparse
} to define
1151 your own actions or types, you'll probably need to define a callback
1152 option. Defining callback options is quite easy; the tricky part is
1153 writing a good callback (the function that is called when
1154 \module{optparse
} encounters the option on the command line).
1156 \subsubsection{Defining a callback option
\label{optparse-defining-callback-option
}}
1158 As always, you can define a callback option either by directly
1159 instantiating the
\class{Option
} class, or by using the
1160 \method{add_option()
} method of your
\class{OptionParser
} object. The
1161 only option attribute you must specify is
\var{callback
}, the function
1165 parser.add_option("-c", callback=my_callback)
1168 Note that you supply a function object here---so you must have
1169 already defined a function
\function{my_callback()
} when you define
1170 the callback option. In this simple case,
\module{optparse
} knows
1171 nothing about the arguments the
\programopt{-c
} option expects to
1172 take. Usually, this means that the option doesn't take any arguments
1173 -- the mere presence of
\programopt{-c
} on the command-line is all it
1174 needs to know. In some circumstances, though, you might want your
1175 callback to consume an arbitrary number of command-line arguments.
1176 This is where writing callbacks gets tricky; it's covered later in
1179 There are several other option attributes that you can supply when you
1180 define an option attribute:
1184 has its usual meaning: as with the ``store'' or ``append'' actions, it
1185 instructs
\module{optparse
} to consume one argument that must be
1186 convertible to
\var{type
}. Rather than storing the value(s) anywhere,
1187 though,
\module{optparse
} converts it to
\var{type
} and passes it to
1188 your callback function.
1191 also has its usual meaning: if it is supplied and
\samp{nargs >
1},
1192 \module{optparse
} will consume
\var{nargs
} arguments, each of which
1193 must be convertible to
\var{type
}. It then passes a tuple of
1194 converted values to your callback.
1196 \term{callback_args
}
1197 a tuple of extra positional arguments to pass to the callback.
1199 \term{callback_kwargs
}
1200 a dictionary of extra keyword arguments to pass to the callback.
1203 \subsubsection{How callbacks are called
\label{optparse-callbacks-called
}}
1205 All callbacks are called as follows:
1208 func(option, opt, value, parser, *args, **kwargs)
1215 is the
\class{Option
} instance that's calling the callback.
1218 is the option string seen on the command-line that's triggering the
1219 callback. (If an abbreviated long option was used,
\var{opt
} will be
1220 the full, canonical option string---for example, if the user puts
1221 \longprogramopt{foo
} on the command-line as an abbreviation for
1222 \longprogramopt{foobar
}, then
\var{opt
} will be
1223 \longprogramopt{foobar
}.)
1226 is the argument to this option seen on the command-line.
1227 \module{optparse
} will only expect an argument if
\var{type
} is
1228 set; the type of
\var{value
} will be the type implied by the
1229 option's type (see~
\ref{optparse-option-types
}, ``Option types''). If
1230 \var{type
} for this option is
\code{None
} (no argument expected), then
1231 \var{value
} will be
\code{None
}. If
\samp{nargs >
1},
\var{value
} will
1232 be a tuple of values of the appropriate type.
1235 is the
\class{OptionParser
} instance driving the whole thing, mainly
1236 useful because you can access some other interesting data through it,
1237 as instance attributes:
1241 the current remaining argument list, i.e. with
\var{opt
} (and
1242 \var{value
}, if any) removed, and only the arguments following
1243 them still there. Feel free to modify
\member{parser.rargs
},
1244 e.g. by consuming more arguments.
1247 the current set of leftover arguments, i.e. arguments that have been
1248 processed but have not been consumed as options (or arguments to
1249 options). Feel free to modify
\member{parser.largs
} e.g. by adding
1250 more arguments to it.
1252 \term{parser.values
}
1253 the object where option values are by default stored. This is useful
1254 because it lets callbacks use the same mechanism as the rest of
1255 \module{optparse
} for storing option values; you don't need to mess
1256 around with globals or closures. You can also access the value(s) of
1257 any options already encountered on the command-line.
1261 is a tuple of arbitrary positional arguments supplied via the
1262 \var{callback
}_args option attribute.
1265 is a dictionary of arbitrary keyword arguments supplied via
1266 \var{callback_kwargs
}.
1269 Since
\var{args
} and
\var{kwargs
} are optional (they are only passed
1270 if you supply
\var{callback_args
} and/or
\var{callback_kwargs
} when
1271 you define your callback option), the minimal callback function is:
1274 def my_callback (option, opt, value, parser):
1278 \subsubsection{Error handling
\label{optparse-callback-error-handling
}}
1280 The callback function should raise
\exception{OptionValueError
} if
1281 there are any problems with the option or its
1282 argument(s).
\module{optparse
} catches this and terminates the
1283 program, printing the error message you supply to stderr. Your
1284 message should be clear, concise, accurate, and mention the option at
1285 fault. Otherwise, the user will have a hard time figuring out what he
1288 \subsubsection{Examples
\label{optparse-callback-examples
}}
1290 Here's an example of a callback option that takes no arguments, and
1291 simply records that the option was seen:
1294 def record_foo_seen (option, opt, value, parser):
1297 parser.add_option("--foo", action="callback", callback=record_foo_seen)
1300 Of course, you could do that with the ``store_true'' action. Here's a
1301 slightly more interesting example: record the fact that
1302 \programopt{-a
} is seen, but blow up if it comes after
\programopt{-b
}
1303 in the command-line.
1306 def check_order (option, opt, value, parser):
1308 raise OptionValueError("can't use -a after -b")
1311 parser.add_option("-a", action="callback", callback=check_order)
1312 parser.add_option("-b", action="store_true", dest="b")
1315 If you want to reuse this callback for several similar options (set a
1316 flag, but blow up if
\programopt{-b
} has already been seen), it needs
1317 a bit of work: the error message and the flag that it sets must be
1321 def check_order (option, opt, value, parser):
1323 raise OptionValueError("can't use
%s after -b" % opt)
1324 setattr(parser.values, option.dest,
1)
1326 parser.add_option("-a", action="callback", callback=check_order, dest='a')
1327 parser.add_option("-b", action="store_true", dest="b")
1328 parser.add_option("-c", action="callback", callback=check_order, dest='c')
1331 Of course, you could put any condition in there---you're not limited
1332 to checking the values of already-defined options. For example, if
1333 you have options that should not be called when the moon is full, all
1334 you have to do is this:
1337 def check_moon (option, opt, value, parser):
1339 raise OptionValueError("
%s option invalid when moon full" % opt)
1340 setattr(parser.values, option.dest,
1)
1342 parser.add_option("--foo",
1343 action="callback", callback=check_moon, dest="foo")
1346 (The definition of
\code{is_full_moon()
} is left as an exercise for the
1349 \strong{Fixed arguments
}
1351 Things get slightly more interesting when you define callback options
1352 that take a fixed number of arguments. Specifying that a callback
1353 option takes arguments is similar to defining a ``store'' or
1354 ``append'' option: if you define
\var{type
}, then the option takes one
1355 argument that must be convertible to that type; if you further define
1356 \var{nargs
}, then the option takes that many arguments.
1358 Here's an example that just emulates the standard ``store'' action:
1361 def store_value (option, opt, value, parser):
1362 setattr(parser.values, option.dest, value)
1364 parser.add_option("--foo",
1365 action="callback", callback=store_value,
1366 type="int", nargs=
3, dest="foo")
1369 Note that
\module{optparse
} takes care of consuming
3 arguments and
1370 converting them to integers for you; all you have to do is store them.
1371 (Or whatever: obviously you don't need a callback for this example.
1372 Use your imagination!)
1374 \strong{Variable arguments
}
1376 Things get hairy when you want an option to take a variable number of
1377 arguments. For this case, you have to write a callback;
1378 \module{optparse
} doesn't provide any built-in capabilities for it.
1379 You have to deal with the full-blown syntax for conventional
\UNIX{}
1380 command-line parsing. (Previously,
\module{optparse
} took care of
1381 this for you, but I got it wrong. It was fixed at the cost of making
1382 this kind of callback more complex.) In particular, callbacks have to
1383 worry about bare
\longprogramopt{} and
\programopt{-
} arguments; the
1387 \item bare
\longprogramopt{}, if not the argument to some option,
1388 causes command-line processing to halt and the
\longprogramopt{}
1391 \item bare
\programopt{-
} similarly causes command-line processing to
1392 halt, but the
\programopt{-
} itself is kept.
1394 \item either
\longprogramopt{} or
\programopt{-
} can be option
1398 If you want an option that takes a variable number of arguments, there
1399 are several subtle, tricky issues to worry about. The exact
1400 implementation you choose will be based on which trade-offs you're
1401 willing to make for your application (which is why
\module{optparse
}
1402 doesn't support this sort of thing directly).
1404 Nevertheless, here's a stab at a callback for an option with variable
1408 def varargs (option, opt, value, parser):
1409 assert value is None
1412 rargs = parser.rargs
1416 # Stop if we hit an arg like "--foo", "-a", "-fx", "--file=f",
1417 # etc. Note that this also stops on "-
3" or "-
3.0", so if
1418 # your option takes numeric values, you will need to handle
1420 if ((arg
[:
2] == "--" and len(arg) >
2) or
1421 (arg
[:
1] == "-" and len(arg) >
1 and arg
[1] != "-")):
1427 setattr(parser.values, option.dest, value)
1430 parser.add_option("-c", "--callback",
1431 action="callback", callback=varargs)
1434 The main weakness with this particular implementation is that negative
1435 numbers in the arguments following
\programopt{-c
} will be interpreted
1436 as further options, rather than as arguments to
\programopt{-c
}.
1437 Fixing this is left as an exercise for the reader.
1439 \subsection{Extending
\module{optparse
}\label{optparse-extending
}}
1441 Since the two major controlling factors in how
\module{optparse
}
1442 interprets command-line options are the action and type of each
1443 option, the most likely direction of extension is to add new actions
1446 Also, the examples section includes several demonstrations of
1447 extending
\module{optparse
} in different ways: e.g. a case-insensitive
1448 option parser, or two kinds of option parsers that implement
1449 ``required options''.
1451 \subsubsection{Adding new types
\label{optparse-adding-types
}}
1453 To add new types, you need to define your own subclass of
1454 \module{optparse
}'s
\class{Option
} class. This class has a couple of
1455 attributes that define
\module{optparse
}'s types:
\member{TYPES
} and
1456 \member{TYPE_CHECKER
}.
1458 \member{TYPES
} is a tuple of type names; in your subclass, simply
1459 define a new tuple
\member{TYPES
} that builds on the standard one.
1461 \member{TYPE_CHECKER
} is a dictionary mapping type names to
1462 type-checking functions. A type-checking function has the following
1466 def check_foo (option : Option, opt : string, value : string)
1470 You can name it whatever you like, and make it return any type you
1471 like. The value returned by a type-checking function will wind up in
1472 the
\class{OptionValues
} instance returned by
1473 \method{OptionParser.parse_args()
}, or be passed to callbacks as the
1474 \var{value
} parameter.
1476 Your type-checking function should raise
\exception{OptionValueError
}
1477 if it encounters any problems.
\exception{OptionValueError
} takes a
1478 single string argument, which is passed as-is to
1479 \class{OptionParser
}'s
\method{error()
} method, which in turn prepends
1480 the program name and the string ``error:'' and prints everything to
1481 stderr before terminating the process.
1483 Here's a silly example that demonstrates adding a ``complex'' option
1484 type to parse Python-style complex numbers on the command line. (This
1485 is even sillier than it used to be, because
\module{optparse
} 1.3 adds
1486 built-in support for complex numbers
[purely for completeness
], but
1489 First, the necessary imports:
1492 from copy import copy
1493 from optparse import Option, OptionValueError
1496 You need to define your type-checker first, since it's referred to
1497 later (in the
\member{TYPE_CHECKER
} class attribute of your
1498 \class{Option
} subclass):
1501 def check_complex (option, opt, value):
1503 return complex(value)
1505 raise OptionValueError(
1506 "option
%s: invalid complex value: %r" % (opt, value))
1509 Finally, the
\class{Option
} subclass:
1512 class MyOption (Option):
1513 TYPES = Option.TYPES + ("complex",)
1514 TYPE_CHECKER = copy(Option.TYPE_CHECKER)
1515 TYPE_CHECKER
["complex"
] = check_complex
1518 (If we didn't make a
\function{copy()
} of
1519 \member{Option.TYPE_CHECKER
}, we would end up modifying the
1520 \member{TYPE_CHECKER
} attribute of
\module{optparse
}'s Option class.
1521 This being Python, nothing stops you from doing that except good
1522 manners and common sense.)
1524 That's it! Now you can write a script that uses the new option type
1525 just like any other
\module{optparse
}-based script, except you have to
1526 instruct your
\class{OptionParser
} to use
\class{MyOption
} instead of
1530 parser = OptionParser(option_class=MyOption)
1531 parser.add_option("-c", action="store", type="complex", dest="c")
1534 Alternately, you can build your own option list and pass it to
1535 \class{OptionParser
}; if you don't use
\method{add_option()
} in the
1536 above way, you don't need to tell
\class{OptionParser
} which option
1540 option_list =
[MyOption("-c", action="store", type="complex", dest="c")
]
1541 parser = OptionParser(option_list=option_list)
1544 \subsubsection{Adding new actions
\label{optparse-adding-actions
}}
1546 Adding new actions is a bit trickier, because you have to understand
1547 that
\module{optparse
} has a couple of classifications for actions:
1550 \term{``store'' actions
}
1551 actions that result in
\module{optparse
} storing a value to an attribute
1552 of the OptionValues instance; these options require a
\var{dest
}
1553 attribute to be supplied to the Option constructor
1554 \term{``typed'' actions
}
1555 actions that take a value from the command line and expect it to be
1556 of a certain type; or rather, a string that can be converted to a
1557 certain type. These options require a
\var{type
} attribute to the
1561 Some default ``store'' actions are
\var{store
},
\var{store_const
},
1562 \var{append
}, and
\var{count
}. The default ``typed'' actions are
1563 \var{store
},
\var{append
}, and
\var{callback
}.
1565 When you add an action, you need to decide if it's a ``store'' action,
1566 a ``typed'', neither, or both. Three class attributes of
1567 \class{Option
} (or your
\class{Option
} subclass) control this:
1569 \begin{memberdesc
}{ACTIONS
}
1570 All actions must be listed as strings in ACTIONS.
1572 \begin{memberdesc
}{STORE_ACTIONS
}
1573 ``store'' actions are additionally listed here.
1575 \begin{memberdesc
}{TYPED_ACTIONS
}
1576 ``typed'' actions are additionally listed here.
1579 In order to actually implement your new action, you must override
1580 \class{Option
}'s
\method{take_action()
} method and add a case that
1581 recognizes your action.
1583 For example, let's add an ``extend'' action. This is similar to the
1584 standard ``append'' action, but instead of taking a single value from
1585 the command-line and appending it to an existing list, ``extend'' will
1586 take multiple values in a single comma-delimited string, and extend an
1587 existing list with them. That is, if
\longprogramopt{names
} is an
1588 ``extend'' option of type string, the command line:
1591 --names=foo,bar --names blah --names ding,dong
1594 would result in a list:
1597 ["foo", "bar", "blah", "ding", "dong"
]
1600 Again we define a subclass of
\class{Option
}:
1603 class MyOption (Option):
1605 ACTIONS = Option.ACTIONS + ("extend",)
1606 STORE_ACTIONS = Option.STORE_ACTIONS + ("extend",)
1607 TYPED_ACTIONS = Option.TYPED_ACTIONS + ("extend",)
1609 def take_action (self, action, dest, opt, value, values, parser):
1610 if action == "extend":
1611 lvalue = value.split(",")
1612 values.ensure_value(dest,
[]).extend(lvalue)
1615 self, action, dest, opt, value, values, parser)
1621 \item ``extend'' both expects a value on the command-line and stores that
1622 value somewhere, so it goes in both
\member{STORE_ACTIONS
} and
1623 \member{TYPED_ACTIONS
}.
1625 \item \method{MyOption.take_action()
} implements just this one new
1626 action, and passes control back to
\method{Option.take_action()
} for
1627 the standard
\module{optparse
} actions.
1629 \item \var{values
} is an instance of the
\class{Values
} class, which
1630 provides the very useful
\method{ensure_value()
}
1631 method.
\method{ensure_value()
} is essentially
\function{getattr()
}
1632 with a safety valve; it is called as:
1635 values.ensure_value(attr, value)
1639 If the
\member{attr
} attribute of
\var{values
} doesn't exist or is
1640 \code{None
}, then
\method{ensure_value()
} first sets it to
\var{value
}, and
1641 then returns
\var{value
}. This is very handy for actions like
1642 ``extend'', ``append'', and ``count'', all of which accumulate data in
1643 a variable and expect that variable to be of a certain type (a list
1644 for the first two, an integer for the latter). Using
1645 \method{ensure_value()
} means that scripts using your action don't
1646 have to worry about setting a default value for the option
1647 destinations in question; they can just leave the default as
\code{None
} and
1648 \method{ensure_value()
} will take care of getting it right when it's
1651 \subsubsection{Other reasons to extend
\module{optparse
}\label{optparse-extending-other-reasons
}}
1653 Adding new types and new actions are the big, obvious reasons why you
1654 might want to extend
\module{optparse
}. I can think of at least two
1655 other areas to play with.
1657 First, the simple one:
\class{OptionParser
} tries to be helpful by
1658 calling
\function{sys.exit()
} when appropriate, i.e. when there's an
1659 error on the command-line or when the user requests help. In the
1660 former case, the traditional course of letting the script crash with a
1661 traceback is unacceptable; it will make users think there's a bug in
1662 your script when they make a command-line error. In the latter case,
1663 there's generally not much point in carrying on after printing a help
1666 If this behaviour bothers you, it shouldn't be too hard to ``fix'' it.
1670 \item subclass OptionParser and override the error() method
1671 \item subclass Option and override the take_action() method---you'll
1672 need to provide your own handling of the ``help'' action that
1673 doesn't call sys.exit()
1676 The second, much more complex, possibility is to override the
1677 command-line syntax implemented by
\module{optparse
}. In this case,
1678 you'd leave the whole machinery of option actions and types alone, but
1679 rewrite the code that processes
\code{sys.argv
}. You'll need to
1680 subclass
\class{OptionParser
} in any case; depending on how radical a
1681 rewrite you want, you'll probably need to override one or all of
1682 \method{parse_args()
},
\method{_process_long_opt()
}, and
1683 \method{_process_short_opts()
}.
1685 Both of these are left as an exercise for the reader. I have not
1686 tried to implement either myself, since I'm quite happy with
1687 \module{optparse
}'s default behaviour (naturally).
1689 Happy hacking, and don't forget: Use the Source, Luke.
1691 \subsubsection{Examples
\label{optparse-extending-examples
}}
1693 Here are a few examples of extending the
\module{optparse
} module.
1695 First, let's change the option-parsing to be case-insensitive:
1697 \verbatiminput{caseless.py
}
1699 And two ways of implementing ``required options'' with
1702 Version
1: Add a method to
\class{OptionParser
} which applications
1703 must call after parsing arguments:
1705 \verbatiminput{required_1.py
}
1707 Version
2: Extend
\class{Option
} and add a
\member{required
}
1708 attribute; extend
\class{OptionParser
} to ensure that required options
1709 are present after parsing:
1711 \verbatiminput{required_2.py
}