1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255
|
#!/usr/bin/env python
#******************************************************************************\
#* Copyright (c) 2003-2004, Martin Blais
#* All rights reserved.
#*
#* Redistribution and use in source and binary forms, with or without
#* modification, are permitted provided that the following conditions are
#* met:
#*
#* * Redistributions of source code must retain the above copyright
#* notice, this list of conditions and the following disclaimer.
#*
#* * Redistributions in binary form must reproduce the above copyright
#* notice, this list of conditions and the following disclaimer in the
#* documentation and/or other materials provided with the distribution.
#*
#* * Neither the name of the Martin Blais, Furius, nor the names of its
#* contributors may be used to endorse or promote products derived from
#* this software without specific prior written permission.
#*
#* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
#* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
#* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
#* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
#* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
#* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
#* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
#* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
#* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
#* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
#* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#******************************************************************************\
"""optparse-commands [<global-opts>] command [<cmd-opts>] [<cmd-args> ...]
Example for implementing programs with command-line interfaces with many
commands, with separate global options and command options.
This script is my template when I create new scripts like that require this
interface. All of the mechanics are implemented using the standard optparse
module that comes with Python >=2.3.
"""
__moredoc__ = """
Each command consists of a class, which has the following properties:
- Must have a class member 'names' which is a list of the names for the command;
- Can optionally have a addopts(self, parser) method which adds options to the
given parser. This defines command options.
"""
__version__ = "$Revision: 1.7 $"
__author__ = "Martin Blais <blais@furius.ca>"
__depends__ = ['Python-2.3']
#===============================================================================
# EXTERNAL DECLARATIONS
#===============================================================================
import sys, os
from os.path import *
import re
from pprint import pprint, pformat
#===============================================================================
# LOCAL DECLARATIONS
#===============================================================================
#===============================================================================
# CLASS CmdSimplest
#===============================================================================
class CmdSimplest:
"""Description of simplest command."""
names = ['simplest']
def execute( self, args ):
print 'Doing something simple.'
#===============================================================================
# CLASS CmdFoo
#===============================================================================
class CmdFoo:
"""Foo command description."""
names = ['foo', 'goo']
def addopts( self, parser ):
parser.add_option('-l', '--local', action='store_true',
help="Some local option.")
def execute( self, args ):
print 'Executing CmdFoo'
pprint(args)
pprint(self.gopts)
pprint(self.opts)
#===============================================================================
# CLASS CmdBar
#===============================================================================
class CmdBar(CmdFoo):
"""Bar command description, derived from foo."""
names = ['bar', 'gore']
def addopts( self, parser ):
CmdFoo.addopts(self, parser)
parser.add_option('-L', '--local-other', action='store_true',
help="Some other local option.")
def execute( self, args ):
print 'Executing CmdBar'
pprint(args)
pprint(self.gopts)
pprint(self.opts)
#===============================================================================
# CLASS CmdHelp
#===============================================================================
class CmdHelp:
"""Help as a command. This is not really necessary."""
names =['help', 'man']
def execute( self, args ):
import optparse
if args:
cmdname = args[0]
try:
sc = subcmds_map[cmdname]
lparser = optparse.OptionParser(sc.__doc__.strip())
if hasattr(sc, 'addopts'):
sc.addopts(lparser)
lparser.print_help()
except KeyError:
raise SystemExit("Error: invalid command '%s'" % cmdname)
else:
gparser.parse_args(['--help'])
#-------------------------------------------------------------------------------
#
def parse_subcommands( gparser, subcmds ):
"""Parse given global arguments, find subcommand from given list of
subcommand objects, parse local arguments and return a tuple of global
options, selected command object, command options, and command arguments.
Call execute() on the command object to run. The command object has members
'gopts' and 'opts' set for global and command options respectively, you
don't need to call execute with those but you could if you wanted to."""
import optparse
global subcmds_map # needed for help command only.
# Build map of name -> command and docstring.
subcmds_map = {}
gparser.usage += '\n\nAvailable Subcommands\n\n'
for sc in subcmds:
gparser.usage += '- %s: %s\n' % (', '.join(sc.names),
sc.__doc__.splitlines()[0])
for n in sc.names:
assert n not in subcmds_map
subcmds_map[n] = sc
# Declare and parse global options.
gparser.disable_interspersed_args()
gopts, args = gparser.parse_args()
if not args:
gparser.print_help()
raise SystemExit("Error: you must specify a command to use.")
subcmdname, subargs = args[0], args[1:]
# Parse command arguments and invoke command.
try:
sc = subcmds_map[subcmdname]
lparser = optparse.OptionParser(sc.__doc__.strip())
if hasattr(sc, 'addopts'):
sc.addopts(lparser)
sc.gopts = gopts
sc.opts, subsubargs = lparser.parse_args(subargs)
except KeyError:
raise SystemExit("Error: invalid command '%s'" % subcmdname)
return sc.gopts, sc, sc.opts, subsubargs
#===============================================================================
# MAIN
#===============================================================================
def main():
# Create global options parser.
global gparser # only need for 'help' command (optional)
import optparse
gparser = optparse.OptionParser(__doc__.strip(), version=__version__)
gparser.add_option('-v', '--verbose', action='store_true',
help="Verbose mode.")
gparser.add_option('-g', '--global', action='store_true',
help="Some global option.")
# Declare subcommands.
subcmds = [
CmdSimplest(),
CmdFoo(),
CmdBar(),
CmdHelp(),
]
gopts, sc, opts, args = parse_subcommands(gparser, subcmds)
sc.execute(args)
#===============================================================================
# TEST
#===============================================================================
def test():
tests = [
'',
'--help',
'help',
'help foo',
'help goo',
'foo',
'goo',
'foo --help',
'bar',
'bar --help',
'bar arg1 arg2',
'bar arg1 --local arg2',
]
print '#!/bin/sh'
for s in tests:
cmd = '%s %s' % (sys.argv[0], s)
print 'clear ; ( echo "%s" ; %s 2>&1 ) | /usr/bin/less' % (cmd, cmd)
# Run as main, otherwise run tests.
if os.environ.has_key('optparse_commands_test'):
test()
elif __name__ == '__main__':
try:
main()
except KeyboardInterrupt:
print "Interrupted, exiting."
|