Mercurial > python-cmd2
comparison cmd2.py @ 38:6d715d7a04fd
proper exit after -h, -v
author | catherine@localhost |
---|---|
date | Tue, 20 May 2008 12:54:54 -0400 |
parents | a974e2f44cbe |
children | 71151157ac7c |
comparison
equal
deleted
inserted
replaced
37:a974e2f44cbe | 38:6d715d7a04fd |
---|---|
19 flagReader.py options are still supported for backward compatibility | 19 flagReader.py options are still supported for backward compatibility |
20 """ | 20 """ |
21 import cmd, re, os, sys, optparse, subprocess, tempfile | 21 import cmd, re, os, sys, optparse, subprocess, tempfile |
22 from optparse import make_option | 22 from optparse import make_option |
23 | 23 |
24 class Option(optparse.Option): | |
25 # optparse.Option.take_action keeps trying to use sys.exit. That's very rude. | |
26 # We don't want to exit, we just want to know so we can terminate a particular | |
27 # function call. | |
28 def take_action(self, action, dest, opt, value, values, parser): | |
29 if action == "help": | |
30 parser.print_help() | |
31 parser.exit() | |
32 setattr(values, '_exit', True) | |
33 elif action == "version": | |
34 parser.print_version() | |
35 parser.exit() | |
36 setattr(values, '_exit', True) | |
37 | |
38 else: | |
39 return optparse.Option.take_action(self, action, dest, opt, value, values, parser) | |
40 | |
41 return 1 | |
42 | |
43 #make_option = Option | |
44 | |
24 class OptionParser(optparse.OptionParser): | 45 class OptionParser(optparse.OptionParser): |
25 def exit(self, status=0, msg=None): | 46 def exit(self, status=0, msg=None): |
47 self.values._exit = True | |
26 if msg: | 48 if msg: |
27 print msg | 49 print msg |
50 # though we must trap and prevent the exit, we also want to end whatever command | |
51 # was called | |
28 | 52 |
29 def error(self, msg): | 53 def error(self, msg): |
30 """error(msg : string) | 54 """error(msg : string) |
31 | 55 |
32 Print a usage message incorporating 'msg' to stderr and exit. | 56 Print a usage message incorporating 'msg' to stderr and exit. |
50 except (optparse.OptionValueError, optparse.BadOptionError, | 74 except (optparse.OptionValueError, optparse.BadOptionError, |
51 optparse.OptionError, optparse.AmbiguousOptionError, | 75 optparse.OptionError, optparse.AmbiguousOptionError, |
52 optparse.OptionConflictError), e: | 76 optparse.OptionConflictError), e: |
53 print e | 77 print e |
54 optionParser.print_help() | 78 optionParser.print_help() |
55 return | 79 return |
80 if hasattr(opts, '_exit'): | |
81 return None | |
56 result = func(instance, arg, opts) | 82 result = func(instance, arg, opts) |
57 return result | 83 return result |
58 newFunc.__doc__ = '%s\n%s' % (func.__doc__, optionParser.format_help()) | 84 newFunc.__doc__ = '%s\n%s' % (func.__doc__, optionParser.format_help()) |
59 return newFunc | 85 return newFunc |
60 return option_setup | 86 return option_setup |