aboutsummaryrefslogtreecommitdiffstats
path: root/defapp.py
diff options
context:
space:
mode:
Diffstat (limited to 'defapp.py')
-rw-r--r--defapp.py95
1 files changed, 95 insertions, 0 deletions
diff --git a/defapp.py b/defapp.py
new file mode 100644
index 0000000..e459084
--- /dev/null
+++ b/defapp.py
@@ -0,0 +1,95 @@
1#!/usr/bin/env python
2
3"""
4A basic Python application shell, for copy&paste development.
5"""
6
7import optparse
8import cmd
9import sys
10
11o = optparse.make_option
12
13class App(cmd.Cmd):
14 def __init__(self, opts=None, defaults=None, no_std_opts=False,
15 stdout=sys.stdout, stderr=sys.stderr, default_cmd=None):
16 cmd.Cmd.__init__(self, None, stdout, stderr)
17 self.default_cmd = default_cmd
18 if not opts:
19 opts = []
20 if not defaults:
21 defaults = {}
22 defaults["_App_file"] = None
23 self.f = None
24 if not no_std_opts:
25 opts += [ o('-o', '--output', action='store', dest='_App_file',
26 help='store output in FILE', metavar='FILE')]
27 (self.options, self.args) = self.__parse(opts, defaults)
28
29 def __parse(self, opts, defaults):
30 parser = optparse.OptionParser(option_list=opts)
31 parser.set_defaults(**defaults)
32 return parser.parse_args()
33
34 def launch(self, args=None):
35 if args:
36 self.args = args
37 try:
38 if self.options._App_file:
39 self.f = open(self.options._App_file, 'w')
40 self.onecmd(' '.join(self.args))
41 except IOError, msg:
42 self.err("I/O Error:", msg)
43 except KeyboardInterrupt:
44 self.err("Interrupted.")
45 if self.f:
46 self.f.close()
47
48 def outfile(self):
49 if self.f:
50 return f
51 else:
52 return sys.stdout
53
54 def emptyline(self):
55 if self.default_cmd:
56 self.onecmd(self.default_cmd)
57
58 def default(self, line):
59 self.err("%s: Command not recognized." % line)
60
61 def do_dump_config(self, key):
62 """Display the configuration as parsed on the console."""
63 def is_private(k): return k[0] == '_'
64 def show(k): print "%20s : %10s" % (k, str(self.options.__dict__[k]))
65 if not key:
66 for x in sorted(self.options.__dict__.keys()):
67 if not is_private(x):
68 show(x)
69 elif not is_private(key) and key in self.options.__dict__:
70 show(key)
71 else:
72 self.err("%s: unknown option." % key)
73
74 @staticmethod
75 def __write(stream, *args, **kargs):
76 stream.write(" ".join([str(a) for a in args]))
77 if not ('omit_newline' in kargs and kargs['omit_newline']):
78 stream.write("\n")
79 stream.flush()
80
81 def err(self, *args, **kargs):
82 self.__write(sys.stderr, *args, **kargs)
83
84 def msg(self, *args, **kargs):
85 self.__write(sys.stdout, *args, **kargs)
86
87 def out(self, *args, **kargs):
88 if self.f:
89 self.__write(self.f, *args, **kargs)
90 else:
91 self.__write(sys.stdout, *args, **kargs)
92
93if __name__ == "__main__":
94 a = App()
95 a.launch()