forked from adeel/timed
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcmdapp.py
53 lines (41 loc) · 987 Bytes
/
cmdapp.py
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
import sys
program = {}
handlers = {}
def main(name, desc):
program['name'] = name
program['desc'] = desc
if len(sys.argv) < 2:
command, args = '', []
else:
command, args = sys.argv[1], sys.argv[2:]
options = {}
for i, arg in enumerate(args):
if arg.startswith('--'):
opt = arg.lstrip('--')
options[opt] = True
del args[i]
if command in handlers:
handler = handlers[command]
else:
handler = help
try:
handler(*args, **options)
except Exception as e:
print e.args
def cmd(handler):
handlers[handler.__name__] = handler
return handler
def default(handler):
handlers[''] = handler
return handler
def help():
subcmds = []
for name, handler in handlers.items():
syntax = (program['name'] + ' ' + name).strip()
usage = ' %s: %s' % (syntax, handler.__doc__)
subcmds.append(usage)
subcmds = '\n'.join(subcmds)
doc = """%s
Usage:
%s""" % (program['desc'], subcmds)
print doc