1888 lines · 72.2 KB · TeX
RawDownload
% THIS FILE IS AUTO-GENERATED!  DO NOT EDIT!% (Your changes will be lost the next time it is generated.)\section{\module{optparse} --- More powerful command line option parser}\declaremodule{standard}{optparse}\moduleauthor{Greg Ward}{gward@python.net}\modulesynopsis{More convenient, flexible, and powerful command-line parsing library.}\versionadded{2.3}\sectionauthor{Greg Ward}{gward@python.net}% An intro blurb used only when generating LaTeX docs for the Python% manual (based on README.txt).  \code{optparse} is a more convenient, flexible, and powerful library forparsing command-line options than \code{getopt}.  \code{optparse} uses a moredeclarative style of command-line parsing: you create an instance of\class{OptionParser}, populate it with options, and parse the command line.\code{optparse} allows users to specify options in the conventional GNU/POSIXsyntax, and additionally generates usage and help messages for you. Here's an example of using \code{optparse} in a simple script:\begin{verbatim}from optparse import OptionParser[...]parser = OptionParser()parser.add_option("-f", "--file", dest="filename",                  help="write report to FILE", metavar="FILE")parser.add_option("-q", "--quiet",                  action="store_false", dest="verbose", default=True,                  help="don't print status messages to stdout") (options, args) = parser.parse_args()\end{verbatim} With these few lines of code, users of your script can now do the``usual thing'' on the command-line, for example:\begin{verbatim}<yourscript> --file=outfile -q\end{verbatim} As it parses the command line, \code{optparse} sets attributes of the\code{options} object returned by \method{parse{\_}args()} based on user-suppliedcommand-line values.  When \method{parse{\_}args()} returns from parsing thiscommand line, \code{options.filename} will be \code{"outfile"} and\code{options.verbose} will be \code{False}.  \code{optparse} supports both longand short options, allows short options to be merged together, andallows options to be associated with their arguments in a variety ofways.  Thus, the following command lines are all equivalent to the aboveexample:\begin{verbatim}<yourscript> -f outfile --quiet<yourscript> --quiet --file outfile<yourscript> -q -foutfile<yourscript> -qfoutfile\end{verbatim} Additionally, users can run one of\begin{verbatim}<yourscript> -h<yourscript> --help\end{verbatim} and \code{optparse} will print out a brief summary of your script'soptions:\begin{verbatim}usage: <yourscript> [options] options:  -h, --help            show this help message and exit  -f FILE, --file=FILE  write report to FILE  -q, --quiet           don't print status messages to stdout\end{verbatim} where the value of \emph{yourscript} is determined at runtime (normallyfrom \code{sys.argv{[}0]}).% $Id: intro.txt 413 2004-09-28 00:59:13Z greg $   \subsection{Background\label{optparse-background}} \module{optparse} was explicitly designed to encourage the creation of programs withstraightforward, conventional command-line interfaces.  To that end, itsupports only the most common command-line syntax and semanticsconventionally used under \UNIX{}.  If you are unfamiliar with theseconventions, read this section to acquaint yourself with them.  \subsubsection{Terminology\label{optparse-terminology}}\begin{description}\item[argument]a string entered on the command-line, and passed by the shell to\code{execl()} or \code{execv()}.  In Python, arguments are elements of\code{sys.argv{[}1:]} (\code{sys.argv{[}0]} is the name of the program beingexecuted).  \UNIX{} shells also use the term ``word''. It is occasionally desirable to substitute an argument list otherthan \code{sys.argv{[}1:]}, so you should read ``argument'' as ``an element of\code{sys.argv{[}1:]}, or of some other list provided as a substitute for\code{sys.argv{[}1:]}''.\item[option   ]an argument used to supply extra information to guide or customize theexecution of a program.  There are many different syntaxes foroptions; the traditional \UNIX{} syntax is a hyphen (``-'') followed by asingle letter, e.g. \code{"-x"} or \code{"-F"}.  Also, traditional \UNIX{}syntax allows multiple options to be merged into a single argument,e.g.  \code{"-x -F"} is equivalent to \code{"-xF"}.  The GNU projectintroduced \code{"-{}-"} followed by a series of hyphen-separated words,e.g. \code{"-{}-file"} or \code{"-{}-dry-run"}.  These are the only two optionsyntaxes provided by \module{optparse}. Some other option syntaxes that the world has seen include:\begin{itemize}\item {} a hyphen followed by a few letters, e.g. \code{"-pf"} (this is\emph{not} the same as multiple options merged into a single argument) \item {} a hyphen followed by a whole word, e.g. \code{"-file"} (this istechnically equivalent to the previous syntax, but they aren'tusually seen in the same program) \item {} a plus sign followed by a single letter, or a few letters,or a word, e.g. \code{"+f"}, \code{"+rgb"} \item {} a slash followed by a letter, or a few letters, or a word, e.g.\code{"/f"}, \code{"/file"} \end{itemize} These option syntaxes are not supported by \module{optparse}, and they never willbe.  This is deliberate: the first three are non-standard on anyenvironment, and the last only makes sense if you're exclusivelytargeting VMS, MS-DOS, and/or Windows.\item[option argument]an argument that follows an option, is closely associated with thatoption, and is consumed from the argument list when that option is.With \module{optparse}, option arguments may either be in a separate argumentfrom their option:\begin{verbatim}-f foo--file foo\end{verbatim} or included in the same argument:\begin{verbatim}-ffoo--file=foo\end{verbatim} Typically, a given option either takes an argument or it doesn't.Lots of people want an ``optional option arguments'' feature, meaningthat some options will take an argument if they see it, and won't ifthey don't.  This is somewhat controversial, because it makes parsingambiguous: if \code{"-a"} takes an optional argument and \code{"-b"} isanother option entirely, how do we interpret \code{"-ab"}?  Because ofthis ambiguity, \module{optparse} does not support this feature.\item[positional argument]something leftover in the argument list after options have beenparsed, i.e. after options and their arguments have been parsed andremoved from the argument list.\item[required option]an option that must be supplied on the command-line; note that thephrase ``required option'' is self-contradictory in English.  \module{optparse}doesn't prevent you from implementing required options, but doesn'tgive you much help at it either.  See \code{examples/required{\_}1.py} and\code{examples/required{\_}2.py} in the \module{optparse} source distribution for twoways to implement required options with \module{optparse}.\end{description} For example, consider this hypothetical command-line:\begin{verbatim}prog -v --report /tmp/report.txt foo bar\end{verbatim} \code{"-v"} and \code{"-{}-report"} are both options.  Assuming that\longprogramopt{report} takes one argument, \code{"/tmp/report.txt"} is an optionargument.  \code{"foo"} and \code{"bar"} are positional arguments.  \subsubsection{What are options for?\label{optparse-what-options-for}} Options are used to provide extra information to tune or customize theexecution of a program.  In case it wasn't clear, options are usually\emph{optional}.  A program should be able to run just fine with no optionswhatsoever.  (Pick a random program from the \UNIX{} or GNU toolsets.  Canit run without any options at all and still make sense?  The mainexceptions are \code{find}, \code{tar}, and \code{dd}{---}all of which are mutantoddballs that have been rightly criticized for their non-standard syntaxand confusing interfaces.) Lots of people want their programs to have ``required options''.  Thinkabout it.  If it's required, then it's \emph{not optional}!  If there is apiece of information that your program absolutely requires in order torun successfully, that's what positional arguments are for. As an example of good command-line interface design, consider the humble\code{cp} utility, for copying files.  It doesn't make much sense to try tocopy files without supplying a destination and at least one source.Hence, \code{cp} fails if you run it with no arguments.  However, it has aflexible, useful syntax that does not require any options at all:\begin{verbatim}cp SOURCE DESTcp SOURCE ... DEST-DIR\end{verbatim} You can get pretty far with just that.  Most \code{cp} implementationsprovide a bunch of options to tweak exactly how the files are copied:you can preserve mode and modification time, avoid following symlinks,ask before clobbering existing files, etc.  But none of this distractsfrom the core mission of \code{cp}, which is to copy either one file toanother, or several files to another directory.  \subsubsection{What are positional arguments for?\label{optparse-what-positional-arguments-for}} Positional arguments are for those pieces of information that yourprogram absolutely, positively requires to run. A good user interface should have as few absolute requirements aspossible.  If your program requires 17 distinct pieces of information inorder to run successfully, it doesn't much matter \emph{how} you get thatinformation from the user{---}most people will give up and walk awaybefore they successfully run the program.  This applies whether the userinterface is a command-line, a configuration file, or a GUI: if you makethat many demands on your users, most of them will simply give up. In short, try to minimize the amount of information that users areabsolutely required to supply{---}use sensible defaults wheneverpossible.  Of course, you also want to make your programs reasonablyflexible.  That's what options are for.  Again, it doesn't matter ifthey are entries in a config file, widgets in the ``Preferences'' dialogof a GUI, or command-line options{---}the more options you implement, themore flexible your program is, and the more complicated itsimplementation becomes.  Too much flexibility has drawbacks as well, ofcourse; too many options can overwhelm users and make your code muchharder to maintain.% $Id: tao.txt 413 2004-09-28 00:59:13Z greg $   \subsection{Tutorial\label{optparse-tutorial}} While \module{optparse} is quite flexible and powerful, it's also straightforward touse in most cases.  This section covers the code patterns that arecommon to any \module{optparse}-based program. First, you need to import the OptionParser class; then, early in themain program, create an OptionParser instance:\begin{verbatim}from optparse import OptionParser[...]parser = OptionParser()\end{verbatim} Then you can start defining options.  The basic syntax is:\begin{verbatim}parser.add_option(opt_str, ...,                  attr=value, ...)\end{verbatim} Each option has one or more option strings, such as \code{"-f"} or\code{"-{}-file"}, and several option attributes that tell \module{optparse} what toexpect and what to do when it encounters that option on the commandline. Typically, each option will have one short option string and one longoption string, e.g.:\begin{verbatim}parser.add_option("-f", "--file", ...)\end{verbatim} You're free to define as many short option strings and as many longoption strings as you like (including zero), as long as there is atleast one option string overall. The option strings passed to \method{add{\_}option()} are effectively labels forthe option defined by that call.  For brevity, we will frequently referto \emph{encountering an option} on the command line; in reality, \module{optparse}encounters \emph{option strings} and looks up options from them. Once all of your options are defined, instruct \module{optparse} to parse yourprogram's command line:\begin{verbatim}(options, args) = parser.parse_args()\end{verbatim} (If you like, you can pass a custom argument list to \method{parse{\_}args()},but that's rarely necessary: by default it uses \code{sys.argv{[}1:]}.) \method{parse{\_}args()} returns two values:\begin{itemize}\item {} \code{options}, an object containing values for all of your options{---}e.g. if \code{"-{}-file"} takes a single string argument, then\code{options.file} will be the filename supplied by the user, or\code{None} if the user did not supply that option \item {} \code{args}, the list of positional arguments leftover after parsingoptions \end{itemize} This tutorial section only covers the four most important optionattributes: \member{action}, \member{type}, \member{dest} (destination), and \member{help}.Of these, \member{action} is the most fundamental.  \subsubsection{Understanding option actions\label{optparse-understanding-option-actions}} Actions tell \module{optparse} what to do when it encounters an option on thecommand line.  There is a fixed set of actions hard-coded into \module{optparse};adding new actions is an advanced topic covered in section~\ref{optparse-extending-optparse}, Extending \module{optparse}.Most actions tell \module{optparse} to store a value in some variable{---}forexample, take a string from the command line and store it in anattribute of \code{options}. If you don't specify an option action, \module{optparse} defaults to \code{store}.  \subsubsection{The store action\label{optparse-store-action}} The most common option action is \code{store}, which tells \module{optparse} to takethe next argument (or the remainder of the current argument), ensurethat it is of the correct type, and store it to your chosen destination. For example:\begin{verbatim}parser.add_option("-f", "--file",                  action="store", type="string", dest="filename")\end{verbatim} Now let's make up a fake command line and ask \module{optparse} to parse it:\begin{verbatim}args = ["-f", "foo.txt"](options, args) = parser.parse_args(args)\end{verbatim} When \module{optparse} sees the option string \code{"-f"}, it consumes the nextargument, \code{"foo.txt"}, and stores it in \code{options.filename}.  So,after this call to \method{parse{\_}args()}, \code{options.filename} is\code{"foo.txt"}. Some other option types supported by \module{optparse} are \code{int} and \code{float}.Here's an option that expects an integer argument:\begin{verbatim}parser.add_option("-n", type="int", dest="num")\end{verbatim} Note that this option has no long option string, which is perfectlyacceptable.  Also, there's no explicit action, since the default is\code{store}. Let's parse another fake command-line.  This time, we'll jam the optionargument right up against the option: since \code{"-n42"} (one argument) isequivalent to \code{"-n 42"} (two arguments), the code\begin{verbatim}(options, args) = parser.parse_args(["-n42"])print options.num\end{verbatim} will print \code{"42"}. If you don't specify a type, \module{optparse} assumes \code{string}.  Combined with thefact that the default action is \code{store}, that means our first examplecan be a lot shorter:\begin{verbatim}parser.add_option("-f", "--file", dest="filename")\end{verbatim} If you don't supply a destination, \module{optparse} figures out a sensible defaultfrom the option strings: if the first long option string is\code{"-{}-foo-bar"}, then the default destination is \code{foo{\_}bar}.  If thereare no long option strings, \module{optparse} looks at the first short optionstring: the default destination for \code{"-f"} is \code{f}. \module{optparse} also includes built-in \code{long} and \code{complex} types.  Addingtypes is covered in section~\ref{optparse-extending-optparse}, Extending \module{optparse}.  \subsubsection{Handling boolean (flag) options\label{optparse-handling-boolean-options}} Flag options{---}set a variable to true or false when a particular optionis seen{---}are quite common.  \module{optparse} supports them with two separateactions, \code{store{\_}true} and \code{store{\_}false}.  For example, you might have a\code{verbose} flag that is turned on with \code{"-v"} and off with \code{"-q"}:\begin{verbatim}parser.add_option("-v", action="store_true", dest="verbose")parser.add_option("-q", action="store_false", dest="verbose")\end{verbatim} Here we have two different options with the same destination, which isperfectly OK.  (It just means you have to be a bit careful when settingdefault values{---}see below.) When \module{optparse} encounters \code{"-v"} on the command line, it sets\code{options.verbose} to \code{True}; when it encounters \code{"-q"},\code{options.verbose} is set to \code{False}.  \subsubsection{Other actions\label{optparse-other-actions}} Some other actions supported by \module{optparse} are:\begin{description}\item[\code{store{\_}const}]store a constant value\item[\code{append}]append this option's argument to a list\item[\code{count}]increment a counter by one\item[\code{callback}]call a specified function\end{description} These are covered in section~\ref{optparse-reference-guide}, Reference Guide and section~\ref{optparse-option-callbacks}, Option Callbacks.  \subsubsection{Default values\label{optparse-default-values}} All of the above examples involve setting some variable (the``destination'') when certain command-line options are seen.  What happensif those options are never seen?  Since we didn't supply any defaults,they are all set to \code{None}.  This is usually fine, but sometimes youwant more control.  \module{optparse} lets you supply a default value for eachdestination, which is assigned before the command line is parsed. First, consider the verbose/quiet example.  If we want \module{optparse} to set\code{verbose} to \code{True} unless \code{"-q"} is seen, then we can do this:\begin{verbatim}parser.add_option("-v", action="store_true", dest="verbose", default=True)parser.add_option("-q", action="store_false", dest="verbose")\end{verbatim} Since default values apply to the \emph{destination} rather than to anyparticular option, and these two options happen to have the samedestination, this is exactly equivalent:\begin{verbatim}parser.add_option("-v", action="store_true", dest="verbose")parser.add_option("-q", action="store_false", dest="verbose", default=True)\end{verbatim} Consider this:\begin{verbatim}parser.add_option("-v", action="store_true", dest="verbose", default=False)parser.add_option("-q", action="store_false", dest="verbose", default=True)\end{verbatim} Again, the default value for \code{verbose} will be \code{True}: the lastdefault value supplied for any particular destination is the one thatcounts. A clearer way to specify default values is the \method{set{\_}defaults()}method of OptionParser, which you can call at any time before calling\method{parse{\_}args()}:\begin{verbatim}parser.set_defaults(verbose=True)parser.add_option(...)(options, args) = parser.parse_args()\end{verbatim} As before, the last value specified for a given option destination isthe one that counts.  For clarity, try to use one method or the other ofsetting default values, not both.  \subsubsection{Generating help\label{optparse-generating-help}} \module{optparse}'s ability to generate help and usage text automatically is usefulfor creating user-friendly command-line interfaces.  All you have to dois supply a \member{help} value for each option, and optionally a short usagemessage for your whole program.  Here's an OptionParser populated withuser-friendly (documented) options:\begin{verbatim}usage = "usage: %prog [options] arg1 arg2"parser = OptionParser(usage=usage)parser.add_option("-v", "--verbose",                  action="store_true", dest="verbose", default=True,                  help="make lots of noise [default]")parser.add_option("-q", "--quiet",                  action="store_false", dest="verbose",                   help="be vewwy quiet (I'm hunting wabbits)")parser.add_option("-f", "--filename",                  metavar="FILE", help="write output to FILE"),parser.add_option("-m", "--mode",                  default="intermediate",                  help="interaction mode: novice, intermediate, "                       "or expert [default: %default]")\end{verbatim} If \module{optparse} encounters either \code{"-h"} or \code{"-{}-help"} on the command-line,or if you just call \method{parser.print{\_}help()}, it prints the following tostandard output:\begin{verbatim}usage: <yourscript> [options] arg1 arg2 options:  -h, --help            show this help message and exit  -v, --verbose         make lots of noise [default]  -q, --quiet           be vewwy quiet (I'm hunting wabbits)  -f FILE, --filename=FILE                        write output to FILE  -m MODE, --mode=MODE  interaction mode: novice, intermediate, or

Lines 1–500 of 1888.