1 "Framework for command line interfaces like CVS. See class CmdFrameWork."
4 class CommandFrameWork
:
6 """Framework class for command line interfaces like CVS.
8 The general command line structure is
10 command [flags] subcommand [subflags] [argument] ...
12 There's a class variable GlobalFlags which specifies the
13 global flags options. Subcommands are defined by defining
14 methods named do_<subcommand>. Flags for the subcommand are
15 defined by defining class or instance variables named
16 flags_<subcommand>. If there's no command, method default()
17 is called. The __doc__ strings for the do_ methods are used
18 for the usage message, printed after the general usage message
19 which is the class variable UsageMessage. The class variable
20 PostUsageMessage is printed after all the do_ methods' __doc__
21 strings. The method's return value can be a suggested exit
22 status. [XXX Need to rewrite this to clarify it.]
24 Common usage is to derive a class, instantiate it, and then call its
25 run() method; by default this takes its arguments from sys.argv[1:].
29 "usage: (name)s [flags] subcommand [subflags] [argument] ..."
31 PostUsageMessage
= None
36 """Constructor, present for completeness."""
39 def run(self
, args
= None):
40 """Process flags, subcommand and options, then run it."""
42 if args
is None: args
= sys
.argv
[1:]
44 opts
, args
= getopt
.getopt(args
, self
.GlobalFlags
)
45 except getopt
.error
, msg
:
46 return self
.usage(msg
)
54 fname
= 'flags_' + cmd
56 method
= getattr(self
, mname
)
57 except AttributeError:
58 return self
.usage("command %r unknown" % (cmd
,))
60 flags
= getattr(self
, fname
)
61 except AttributeError:
64 opts
, args
= getopt
.getopt(args
[1:], flags
)
65 except getopt
.error
, msg
:
67 "subcommand %s: " % cmd
+ str(msg
))
69 return method(opts
, args
)
71 def options(self
, opts
):
72 """Process the options retrieved by getopt.
73 Override this if you have any options."""
78 print 'option', o
, 'value', repr(a
)
82 """Called just before calling the subcommand."""
85 def usage(self
, msg
= None):
86 """Print usage message. Return suitable exit code (2)."""
88 print self
.UsageMessage
% {'name': self
.__class
__.__name
__}
94 if docstrings
.has_key(name
):
97 doc
= getattr(c
, name
).__doc
__
101 docstrings
[name
] = doc
106 print "where subcommand can be:"
107 names
= docstrings
.keys()
110 print docstrings
[name
]
111 if self
.PostUsageMessage
:
112 print self
.PostUsageMessage
116 """Default method, called when no subcommand is given.
117 You should always override this."""
118 print "Nobody expects the Spanish Inquisition!"
122 """Test script -- called when this module is run as a script."""
124 class Hello(CommandFrameWork
):
125 def do_hello(self
, opts
, args
):
126 "hello -- print 'hello world', needs no arguments"
138 print '-'*10, t
, '-'*10
140 print "Exit status:", repr(sts
)
143 if __name__
== '__main__':