3 # XXX Python script template
5 # XXX Describe what the script does here.
12 class Usage(Exception):
13 def __init__(self
, msg
):
18 Representation of a command to be executed.
21 def __init__(self
, dictionary
={}):
22 self
.subst_dictionary(dictionary
)
24 def subst_dictionary(self
, dictionary
):
25 self
._subst
_dictionary
= dictionary
27 def subst(self
, string
, dictionary
=None):
29 Substitutes (via the format operator) the values in the specified
30 dictionary into the specified command.
32 The command can be an (action, string) tuple. In all cases, we
33 perform substitution on strings and don't worry if something isn't
34 a string. (It's probably a Python function to be executed.)
36 if dictionary
is None:
37 dictionary
= self
._subst
_dictionary
40 string
= string
% dictionary
45 def do_display(self
, string
):
46 if isinstance(string
, tuple):
49 s
= '%s(%s)' % (func
.__name
__, ', '.join(map(repr, args
)))
51 s
= self
.subst(string
)
52 if not s
.endswith('\n'):
57 def do_not_display(self
, string
):
60 def do_execute(self
, command
):
61 if isinstance(command
, str):
62 command
= self
.subst(command
)
63 cmdargs
= shlex
.split(command
)
64 if cmdargs
[0] == 'cd':
65 command
= (os
.chdir
,) + tuple(cmdargs
[1:])
66 elif cmdargs
[0] == 'mkdir':
67 command
= (os
.mkdir
,) + tuple(cmdargs
[1:])
68 if isinstance(command
, tuple):
73 return os
.system(command
)
75 def do_not_execute(self
, command
):
81 def run(self
, command
, display
=None):
83 Runs this command, displaying it first.
85 The actual display() and execute() methods we call may be
86 overridden if we're printing but not executing, or vice versa.
91 return self
.execute(command
)
98 long_options
= ['help', 'no-exec', 'quiet']
101 Usage: script-template.py [-hnq]
103 -h, --help Print this help and exit
104 -n, --no-exec No execute, just print command lines
105 -q, --quiet Quiet, don't print command lines
110 opts
, args
= getopt
.getopt(argv
[1:], short_options
, long_options
)
111 except getopt
.error
as msg
:
115 if o
in ('-h', '--help'):
118 elif o
in ('-n', '--no-exec'):
119 Command
.execute
= Command
.do_not_execute
120 elif o
in ('-q', '--quiet'):
121 Command
.display
= Command
.do_not_display
123 sys
.stderr
.write(err
.msg
)
124 sys
.stderr
.write('use -h to get help')
130 for command
in [ Command(c
) for c
in commands
]:
131 status
= command
.run(command
)
135 if __name__
== "__main__":
140 # indent-tabs-mode:nil
142 # vim: set expandtab tabstop=4 shiftwidth=4: