Mercurial > python-cmd2
comparison cmd2.py @ 15:0eb8d4e18472
fixed error handling
author | catherine@localhost |
---|---|
date | Thu, 15 May 2008 13:34:11 -0400 |
parents | a242603905d9 |
children | c8efa4369189 24fbec27d66f |
comparison
equal
deleted
inserted
replaced
14:a242603905d9 | 15:0eb8d4e18472 |
---|---|
22 from optparse import make_option | 22 from optparse import make_option |
23 | 23 |
24 class OptionParser(optparse.OptionParser): | 24 class OptionParser(optparse.OptionParser): |
25 def exit(self, status=0, msg=None): | 25 def exit(self, status=0, msg=None): |
26 if msg: | 26 if msg: |
27 sys.stderr.write(msg) | 27 print msg |
28 | 28 |
29 def error(self, msg): | 29 def error(self, msg): |
30 """error(msg : string) | 30 """error(msg : string) |
31 | 31 |
32 Print a usage message incorporating 'msg' to stderr and exit. | 32 Print a usage message incorporating 'msg' to stderr and exit. |
33 If you override this in a subclass, it should not return -- it | 33 If you override this in a subclass, it should not return -- it |
34 should either exit or raise an exception. | 34 should either exit or raise an exception. |
35 """ | 35 """ |
36 self.stderr.write(msg) | 36 #print msg |
37 self.print_usage(sys.stderr) | 37 #print self.format_help() |
38 raise | |
38 | 39 |
39 def options(option_list): | 40 def options(option_list): |
40 def option_setup(func): | 41 def option_setup(func): |
41 optionParser = OptionParser() | 42 optionParser = OptionParser() |
42 for opt in option_list: | 43 for opt in option_list: |
43 optionParser.add_option(opt) | 44 optionParser.add_option(opt) |
44 optionParser.set_usage("%s [options] arg" % func.__name__.strip('do_')) | 45 optionParser.set_usage("%s [options] arg" % func.__name__.strip('do_')) |
45 def newFunc(instance, arg): | 46 def newFunc(instance, arg): |
46 try: | 47 try: |
47 opts, arg = optionParser.parse_args(arg.split()) | 48 opts, arg = optionParser.parse_args(arg.split()) |
48 except optparse.OptionValueError, e: | 49 except optparse.OptionValueError, e: |
49 print e | 50 print e |
50 optionParser.print_help() | 51 optionParser.print_help() |
51 return | 52 return |
52 result = func(instance, arg, opts) | 53 result = func(instance, arg, opts) |
53 #import pdb; pdb.set_trace() | |
54 return result | 54 return result |
55 newFunc.__doc__ = '%s\n%s' % (func.__doc__, optionParser.format_help()) | 55 newFunc.__doc__ = '%s\n%s' % (func.__doc__, optionParser.format_help()) |
56 return newFunc | 56 return newFunc |
57 return option_setup | 57 return option_setup |
58 | 58 |