3 # XXX Python script template
5 # XXX Describe what the script does here.
13 class Usage(Exception):
14 def __init__(self, msg):
19 Representation of a command to be executed.
22 def __init__(self, dictionary={}):
23 self.subst_dictionary(dictionary)
25 def subst_dictionary(self, dictionary):
26 self._subst_dictionary = dictionary
28 def subst(self, string, dictionary=None):
30 Substitutes (via the format operator) the values in the specified
31 dictionary into the specified command.
33 The command can be an (action, string) tuple. In all cases, we
34 perform substitution on strings and don't worry if something isn't
35 a string. (It's probably a Python function to be executed.)
37 if dictionary is None:
38 dictionary = self._subst_dictionary
41 string = string % dictionary
46 def do_display(self, string):
47 if type(string) == type(()):
50 s = '%s(%s)' % (func.__name__, ', '.join(map(repr, args)))
52 s = self.subst(string)
53 if not s.endswith('\n'):
58 def do_not_display(self, string):
61 def do_execute(self, command):
62 if type(command) == type(''):
63 command = self.subst(command)
64 cmdargs = shlex.split(command)
65 if cmdargs[0] == 'cd':
66 command = (os.chdir,) + tuple(cmdargs[1:])
67 elif cmdargs[0] == 'mkdir':
68 command = (os.mkdir,) + tuple(cmdargs[1:])
69 if type(command) == type(()):
74 return os.system(command)
76 def do_not_execute(self, command):
82 def run(self, command, display=None):
84 Runs this command, displaying it first.
86 The actual display() and execute() methods we call may be
87 overridden if we're printing but not executing, or vice versa.
92 return self.execute(command)
99 long_options = ['help', 'no-exec', 'quiet']
102 Usage: script-template.py [-hnq]
104 -h, --help Print this help and exit
105 -n, --no-exec No execute, just print command lines
106 -q, --quiet Quiet, don't print command lines
111 opts, args = getopt.getopt(argv[1:], short_options, long_options)
112 except getopt.error, msg:
116 if o in ('-h', '--help'):
119 elif o in ('-n', '--no-exec'):
120 Command.execute = Command.do_not_execute
121 elif o in ('-q', '--quiet'):
122 Command.display = Command.do_not_display
124 sys.stderr.write(err.msg)
125 sys.stderr.write('use -h to get help')
131 for command in [ Command(c) for c in commands ]:
132 status = command.run(command)
136 if __name__ == "__main__":
141 # indent-tabs-mode:nil
143 # vim: set expandtab tabstop=4 shiftwidth=4: