Package grizzled :: Module cmdline
[hide private]
[frames] | no frames]

Source Code for Module grizzled.cmdline

 1  #!/usr/bin/env python 
 2  # --------------------------------------------------------------------------- 
 3   
 4  """ 
 5  Provides a front-end to the Python standard ``optparse`` module. The 
 6  ``CommandLineParser`` class makes two changes to the standard behavior. 
 7   
 8    - The output for the '-h' option is slightly different. 
 9    - A bad option causes the parser to generate the entire usage output, 
10      not just an error message. 
11   
12  It also provides a couple extra utility modules. 
13  """ 
14   
15  __docformat__ = "restructuredtext en" 
16   
17  # --------------------------------------------------------------------------- 
18  # Imports 
19  # --------------------------------------------------------------------------- 
20   
21  from optparse import OptionParser 
22  import sys 
23   
24  # --------------------------------------------------------------------------- 
25  # Exports 
26  # --------------------------------------------------------------------------- 
27   
28  __all__ = ['CommandLineParser'] 
29   
30  # --------------------------------------------------------------------------- 
31  # Classes 
32  # --------------------------------------------------------------------------- 
33   
34 -class CommandLineParser(OptionParser):
35 """Custom version of command line option parser.""" 36
37 - def __init__(self, *args, **kw):
38 """ Create a new instance. """ 39 40 OptionParser.__init__(self, *args, **kw) 41 42 # I like my help option message better than the default... 43 44 self.remove_option('-h') 45 self.add_option('-h', '--help', action='help', 46 help='Show this message and exit.') 47 48 self.epilogue = None
49
50 - def print_help(self, out=sys.stderr):
51 """ 52 Print the help message, followed by the epilogue (if set), to the 53 specified output file. You can define an epilogue by setting the 54 ``epilogue`` field. 55 56 :Parameters: 57 out : file 58 where to write the usage message 59 """ 60 OptionParser.print_help(self, out) 61 if self.epilogue: 62 import textwrap 63 print >> out, '\n%s' % textwrap.fill(self.epilogue, 80) 64 out.flush()
65
66 - def die_with_usage(self, msg=None, exit_code=2):
67 """ 68 Display a usage message and exit. 69 70 :Parameters: 71 msg : str 72 If not set to ``None`` (the default), this message will be 73 displayed before the usage message 74 75 exit_code : int 76 The process exit code. Defaults to 2. 77 """ 78 if msg != None: 79 print >> sys.stderr, msg 80 self.print_help(sys.stderr) 81 sys.exit(exit_code)
82
83 - def error(self, msg):
84 """ 85 Overrides parent ``OptionParser`` class's ``error()`` method and 86 forces the full usage message on error. 87 """ 88 sys.stderr.write("%s: error: %s\n" % (self.get_prog_name(), msg)) 89 self.die_with_usage(msg)
90