[Python-checkins] python/dist/src/Doc/lib caseless.py,NONE,1.1 liboptparse.tex,NONE,1.1 required_1.py,NONE,1.1 required_2.py,NONE,1.1 lib.tex,1.211,1.212
nnorwitz@users.sourceforge.net
nnorwitz@users.sourceforge.net
Mon, 06 Jan 2003 08:51:39 -0800
Update of /cvsroot/python/python/dist/src/Doc/lib
In directory sc8-pr-cvs1:/tmp/cvs-serv13119/lib
Modified Files:
lib.tex
Added Files:
caseless.py liboptparse.tex required_1.py required_2.py
Log Message:
SF #642236, optparse LaTeX docs by Johannes Gijsbers
--- NEW FILE: caseless.py ---
from optparse import Option, OptionParser, _match_abbrev
# This case-insensitive option parser relies on having a
# case-insensitive dictionary type available. Here's one
# for Python 2.2. Note that a *real* case-insensitive
# dictionary type would also have to implement __new__(),
# update(), and setdefault() -- but that's not the point
# of this exercise.
class caseless_dict (dict):
def __setitem__ (self, key, value):
dict.__setitem__(self, key.lower(), value)
def __getitem__ (self, key):
return dict.__getitem__(self, key.lower())
def get (self, key, default=None):
return dict.get(self, key.lower())
def has_key (self, key):
return dict.has_key(self, key.lower())
class CaselessOptionParser (OptionParser):
def _create_option_list (self):
self.option_list = []
self._short_opt = caseless_dict()
self._long_opt = caseless_dict()
self._long_opts = []
self.defaults = {}
def _match_long_opt (self, opt):
return _match_abbrev(opt.lower(), self._long_opt.keys())
if __name__ == "__main__":
from optik.errors import OptionConflictError
# test 1: no options to start with
parser = CaselessOptionParser()
try:
parser.add_option("-H", dest="blah")
except OptionConflictError:
print "ok: got OptionConflictError for -H"
else:
print "not ok: no conflict between -h and -H"
parser.add_option("-f", "--file", dest="file")
#print `parser.get_option("-f")`
#print `parser.get_option("-F")`
#print `parser.get_option("--file")`
#print `parser.get_option("--fIlE")`
(options, args) = parser.parse_args(["--FiLe", "foo"])
assert options.file == "foo", options.file
print "ok: case insensitive long options work"
(options, args) = parser.parse_args(["-F", "bar"])
assert options.file == "bar", options.file
print "ok: case insensitive short options work"
--- NEW FILE: liboptparse.tex ---
\section{\module{optparse} ---
Powerful parser for command line options.}
\declaremodule{standard}{optparse}
\moduleauthor{Greg Ward}{gward@python.net}
\sectionauthor{Johannes Gijsbers}{jlgijsbers@users.sf.net}
\sectionauthor{Greg Ward}{gward@python.net}
\modulesynopsis{Powerful, flexible, extensible, easy-to-use command-line
parsing library.}
\versionadded{2.3}
The \module{optparse} module is a powerful, flexible, extensible,
easy-to-use command-line parsing library for Python. Using
\module{optparse}, you can add intelligent, sophisticated handling of
command-line options to your scripts with very little overhead.
Here's an example of using \module{optparse} to add some command-line
[...1654 lines suppressed...]
Here are a few examples of extending the \module{optparse} module.
First, let's change the option-parsing to be case-insensitive:
\verbatiminput{caseless.py}
And two ways of implementing ``required options'' with
\module{optparse}.
Version 1: Add a method to \class{OptionParser} which applications
must call after parsing arguments:
\verbatiminput{required_1.py}
Version 2: Extend \class{Option} and add a \member{required}
attribute; extend \class{OptionParser} to ensure that required options
are present after parsing:
\verbatiminput{required_2.py}
--- NEW FILE: required_1.py ---
import optparse
class OptionParser (optparse.OptionParser):
def check_required (self, opt):
option = self.get_option(opt)
# Assumes the option's 'default' is set to None!
if getattr(self.values, option.dest) is None:
self.error("%s option not supplied" % option)
parser = OptionParser()
parser.add_option("-v", action="count", dest="verbose")
parser.add_option("-f", "--file", default=None)
(options, args) = parser.parse_args()
print "verbose:", options.verbose
print "file:", options.file
parser.check_required("-f")
--- NEW FILE: required_2.py ---
import optparse
class Option (optparse.Option):
ATTRS = optparse.Option.ATTRS + ['required']
def _check_required (self):
if self.required and not self.takes_value():
raise OptionError(
"required flag set for option that doesn't take a value",
self)
# Make sure _check_required() is called from the constructor!
CHECK_METHODS = optparse.Option.CHECK_METHODS + [_check_required]
def process (self, opt, value, values, parser):
optparse.Option.process(self, opt, value, values, parser)
parser.option_seen[self] = 1
class OptionParser (optparse.OptionParser):
def _init_parsing_state (self):
optparse.OptionParser._init_parsing_state(self)
self.option_seen = {}
def check_values (self, values, args):
for option in self.option_list:
if (isinstance(option, Option) and
option.required and
not self.option_seen.has_key(option)):
self.error("%s not supplied" % option)
return (values, args)
parser = OptionParser(option_list=[
Option("-v", action="count", dest="verbose"),
Option("-f", "--file", required=1)])
(options, args) = parser.parse_args()
print "verbose:", options.verbose
print "file:", options.file
Index: lib.tex
===================================================================
RCS file: /cvsroot/python/python/dist/src/Doc/lib/lib.tex,v
retrieving revision 1.211
retrieving revision 1.212
diff -C2 -d -r1.211 -r1.212
*** lib.tex 5 Jan 2003 23:19:41 -0000 1.211
--- lib.tex 6 Jan 2003 16:51:34 -0000 1.212
***************
*** 152,155 ****
--- 152,156 ----
\input{libcursespanel}
\input{libgetopt}
+ \input{liboptparse}
\input{libtempfile}
\input{liberrno}