Back to index

python3.2  3.2.2
Public Member Functions | Public Attributes | Static Public Attributes
CommandLine.Application Class Reference
Inheritance diagram for CommandLine.Application:
Inheritance graph
[legend]
Collaboration diagram for CommandLine.Application:
Collaboration graph
[legend]

List of all members.

Public Member Functions

def __init__
def add_option
def startup
def exit
def parse
def check_files
def help
def notice
def print_header
def print_options
def handle_files
def handle_h
def handle_v
def handle__help
def handle__debug
def handle__copyright
def handle__examples
def main

Public Attributes

 filename
 name
 header
 arguments
 option_map
 verbose
 debug

Static Public Attributes

list options = []
list preset_options
string header = ''
string name = ''
string synopsis = '%(name)s [option] files...'
string version = ''
string about = ''
string examples = ''
 copyright = __copyright__
int globbing = 1
int debug = 0
int verbose = 0
 InternalError = BaseException
 values = None
 files = None
 optionlist = None

Detailed Description

Command line application interface with builtin argument
    parsing.

Definition at line 227 of file CommandLine.py.


Constructor & Destructor Documentation

def CommandLine.Application.__init__ (   self,
  argv = None 
)

Definition at line 306 of file CommandLine.py.

00306 
00307     def __init__(self,argv=None):
00308 
00309         # Setup application specs
00310         if argv is None:
00311             argv = sys.argv
00312         self.filename = os.path.split(argv[0])[1]
00313         if not self.name:
00314             self.name = os.path.split(self.filename)[1]
00315         else:
00316             self.name = self.name
00317         if not self.header:
00318             self.header = self.name
00319         else:
00320             self.header = self.header
00321 
00322         # Init .arguments list
00323         self.arguments = argv[1:]
00324 
00325         # Setup Option mapping
00326         self.option_map = option_dict(self.options)
00327 
00328         # Append preset options
00329         for option in self.preset_options:
00330             if not option.name in self.option_map:
00331                 self.add_option(option)
00332 
00333         # Init .files list
00334         self.files = []
00335 
00336         # Start Application
00337         rc = 0
00338         try:
00339             # Process startup
00340             rc = self.startup()
00341             if rc is not None:
00342                 raise SystemExit(rc)
00343 
00344             # Parse command line
00345             rc = self.parse()
00346             if rc is not None:
00347                 raise SystemExit(rc)
00348 
00349             # Start application
00350             rc = self.main()
00351             if rc is None:
00352                 rc = 0
00353 
00354         except SystemExit as rcException:
00355             rc = rcException
00356             pass
00357 
00358         except KeyboardInterrupt:
00359             print()
00360             print('* User Break')
00361             print()
00362             rc = 1
00363 
00364         except self.InternalError:
00365             print()
00366             print('* Internal Error (use --debug to display the traceback)')
00367             if self.debug:
00368                 print()
00369                 traceback.print_exc(20, sys.stdout)
00370             elif self.verbose:
00371                 print('  %s: %s' % sys.exc_info()[:2])
00372             print()
00373             rc = 1
00374 
00375         raise SystemExit(rc)

Here is the caller graph for this function:


Member Function Documentation

def CommandLine.Application.add_option (   self,
  option 
)
Add a new Option instance to the Application dynamically.

    Note that this has to be done *before* .parse() is being
    executed.

Definition at line 376 of file CommandLine.py.

00376 
00377     def add_option(self, option):
00378 
00379         """ Add a new Option instance to the Application dynamically.
00380 
00381             Note that this has to be done *before* .parse() is being
00382             executed.
00383 
00384         """
00385         self.options.append(option)
00386         self.option_map[option.name] = option

def CommandLine.Application.check_files (   self,
  filelist 
)
Apply some user defined checks on the files given in filelist.

    This may modify filelist in place. A typical application
    is checking that at least n files are given.

    If this method returns anything other than None, the
    process is terminated with the return value as exit code.

Definition at line 482 of file CommandLine.py.

00482 
00483     def check_files(self,filelist):
00484 
00485         """ Apply some user defined checks on the files given in filelist.
00486 
00487             This may modify filelist in place. A typical application
00488             is checking that at least n files are given.
00489 
00490             If this method returns anything other than None, the
00491             process is terminated with the return value as exit code.
00492 
00493         """
00494         return None

Here is the caller graph for this function:

def CommandLine.Application.exit (   self,
  rc = 0 
)
Exit the program.

    rc is used as exit code and passed back to the calling
    program. It defaults to 0 which usually means: OK.

Definition at line 397 of file CommandLine.py.

00397 
00398     def exit(self, rc=0):
00399 
00400         """ Exit the program.
00401 
00402             rc is used as exit code and passed back to the calling
00403             program. It defaults to 0 which usually means: OK.
00404 
00405         """
00406         raise SystemExit(rc)

def CommandLine.Application.handle__copyright (   self,
  arg 
)

Definition at line 588 of file CommandLine.py.

00588 
00589     def handle__copyright(self,arg):
00590 
00591         self.print_header()
00592         copyright = self.copyright % self.__dict__
00593         print(copyright.strip())
00594         print()
00595         return 0

Here is the call graph for this function:

def CommandLine.Application.handle__debug (   self,
  arg 
)

Definition at line 581 of file CommandLine.py.

00581 
00582     def handle__debug(self,arg):
00583 
00584         self.debug = 1
00585         # We don't want to catch internal errors:
00586         class NoErrorToCatch(Exception): pass
00587         self.InternalError = NoErrorToCatch

def CommandLine.Application.handle__examples (   self,
  arg 
)

Definition at line 596 of file CommandLine.py.

00596 
00597     def handle__examples(self,arg):
00598 
00599         self.print_header()
00600         if self.examples:
00601             print('Examples:')
00602             print()
00603             examples = self.examples % self.__dict__
00604             print(examples.strip())
00605             print()
00606         else:
00607             print('No examples available.')
00608             print()
00609         return 0

Here is the call graph for this function:

def CommandLine.Application.handle__help (   self,
  arg 
)

Definition at line 576 of file CommandLine.py.

00576 
00577     def handle__help(self,arg):
00578 
00579         self.help()
00580         return 0

Here is the call graph for this function:

def CommandLine.Application.handle_files (   self,
  files 
)
This may process the files list in place.

Definition at line 557 of file CommandLine.py.

00557 
00558     def handle_files(self,files):
00559 
00560         """ This may process the files list in place.
00561         """
00562         return None

Here is the caller graph for this function:

def CommandLine.Application.handle_h (   self,
  arg 
)

Definition at line 564 of file CommandLine.py.

00564 
00565     def handle_h(self,arg):
00566 
00567         self.help()
00568         return 0

Here is the call graph for this function:

def CommandLine.Application.handle_v (   self,
  value 
)
Turn on verbose output.

Definition at line 569 of file CommandLine.py.

00569 
00570     def handle_v(self, value):
00571 
00572         """ Turn on verbose output.
00573         """
00574         self.verbose = 1

def CommandLine.Application.help (   self,
  note = '' 
)

Definition at line 495 of file CommandLine.py.

00495 
00496     def help(self,note=''):
00497 
00498         self.print_header()
00499         if self.synopsis:
00500             print('Synopsis:')
00501             # To remain backward compatible:
00502             try:
00503                 synopsis = self.synopsis % self.name
00504             except (NameError, KeyError, TypeError):
00505                 synopsis = self.synopsis % self.__dict__
00506             print(' ' + synopsis)
00507         print()
00508         self.print_options()
00509         if self.version:
00510             print('Version:')
00511             print(' %s' % self.version)
00512             print()
00513         if self.about:
00514             about = self.about % self.__dict__
00515             print(about.strip())
00516             print()
00517         if note:
00518             print('-'*72)
00519             print('Note:',note)
00520             print()

Here is the call graph for this function:

Here is the caller graph for this function:

Override this method as program entry point.

    The return value is passed to sys.exit() as argument.  If
    it is None, 0 is assumed (meaning OK). Unhandled
    exceptions are reported with exit status code 1 (see
    __init__ for further details).

Reimplemented in pybench.PyBenchCmdline.

Definition at line 610 of file CommandLine.py.

00610 
00611     def main(self):
00612 
00613         """ Override this method as program entry point.
00614 
00615             The return value is passed to sys.exit() as argument.  If
00616             it is None, 0 is assumed (meaning OK). Unhandled
00617             exceptions are reported with exit status code 1 (see
00618             __init__ for further details).
00619 
00620         """
00621         return None
00622 
# Alias
def CommandLine.Application.notice (   self,
  note 
)

Definition at line 521 of file CommandLine.py.

00521 
00522     def notice(self,note):
00523 
00524         print('-'*72)
00525         print('Note:',note)
00526         print('-'*72)
00527         print()

Parse the command line and fill in self.values and self.files.

    After having parsed the options, the remaining command line
    arguments are interpreted as files and passed to .handle_files()
    for processing.

    As final step the option handlers are called in the order
    of the options given on the command line.

Definition at line 407 of file CommandLine.py.

00407 
00408     def parse(self):
00409 
00410         """ Parse the command line and fill in self.values and self.files.
00411 
00412             After having parsed the options, the remaining command line
00413             arguments are interpreted as files and passed to .handle_files()
00414             for processing.
00415 
00416             As final step the option handlers are called in the order
00417             of the options given on the command line.
00418 
00419         """
00420         # Parse arguments
00421         self.values = values = {}
00422         for o in self.options:
00423             if o.has_default:
00424                 values[o.prefix+o.name] = o.default
00425             else:
00426                 values[o.prefix+o.name] = 0
00427         flags,lflags = _getopt_flags(self.options)
00428         try:
00429             optlist,files = getopt.getopt(self.arguments,flags,lflags)
00430             if self.globbing:
00431                 l = []
00432                 for f in files:
00433                     gf = glob.glob(f)
00434                     if not gf:
00435                         l.append(f)
00436                     else:
00437                         l[len(l):] = gf
00438                 files = l
00439             self.optionlist = optlist
00440             self.files = files + self.files
00441         except getopt.error as why:
00442             self.help(why)
00443             sys.exit(1)
00444 
00445         # Call file handler
00446         rc = self.handle_files(self.files)
00447         if rc is not None:
00448             sys.exit(rc)
00449 
00450         # Call option handlers
00451         for optionname, value in optlist:
00452 
00453             # Try to convert value to integer
00454             try:
00455                 value = int(value)
00456             except ValueError:
00457                 pass
00458 
00459             # Find handler and call it (or count the number of option
00460             # instances on the command line)
00461             handlername = 'handle' + optionname.replace('-', '_')
00462             try:
00463                 handler = getattr(self, handlername)
00464             except AttributeError:
00465                 if value == '':
00466                     # count the number of occurances
00467                     if optionname in values:
00468                         values[optionname] = values[optionname] + 1
00469                     else:
00470                         values[optionname] = 1
00471                 else:
00472                     values[optionname] = value
00473             else:
00474                 rc = handler(value)
00475                 if rc is not None:
00476                     raise SystemExit(rc)
00477 
00478         # Apply final file check (for backward compatibility)
00479         rc = self.check_files(self.files)
00480         if rc is not None:
00481             sys.exit(rc)

Here is the call graph for this function:

Here is the caller graph for this function:

Definition at line 528 of file CommandLine.py.

00528 
00529     def print_header(self):
00530 
00531         print('-'*72)
00532         print(self.header % self.__dict__)
00533         print('-'*72)
00534         print()

Here is the caller graph for this function:

Definition at line 535 of file CommandLine.py.

00535 
00536     def print_options(self):
00537 
00538         options = self.options
00539         print('Options and default settings:')
00540         if not options:
00541             print('  None')
00542             return
00543         int = [x for x in options if x.prefix == '--']
00544         short = [x for x in options if x.prefix == '-']
00545         items = short + int
00546         for o in options:
00547             print(' ',o)
00548         print()

Here is the caller graph for this function:

Set user defined instance variables.

    If this method returns anything other than None, the
    process is terminated with the return value as exit code.

Definition at line 387 of file CommandLine.py.

00387 
00388     def startup(self):
00389 
00390         """ Set user defined instance variables.
00391 
00392             If this method returns anything other than None, the
00393             process is terminated with the return value as exit code.
00394 
00395         """
00396         return None


Member Data Documentation

Reimplemented in pybench.PyBenchCmdline.

Definition at line 280 of file CommandLine.py.

Definition at line 322 of file CommandLine.py.

Reimplemented in pybench.PyBenchCmdline.

Definition at line 286 of file CommandLine.py.

Reimplemented in pybench.PyBenchCmdline.

Definition at line 292 of file CommandLine.py.

Reimplemented in pybench.PyBenchCmdline.

Definition at line 583 of file CommandLine.py.

Definition at line 283 of file CommandLine.py.

Definition at line 311 of file CommandLine.py.

Definition at line 303 of file CommandLine.py.

Definition at line 289 of file CommandLine.py.

Reimplemented in pybench.PyBenchCmdline.

Definition at line 268 of file CommandLine.py.

Reimplemented in pybench.PyBenchCmdline.

Definition at line 317 of file CommandLine.py.

CommandLine.Application.InternalError = BaseException [static]

Definition at line 298 of file CommandLine.py.

Definition at line 271 of file CommandLine.py.

Definition at line 313 of file CommandLine.py.

Definition at line 325 of file CommandLine.py.

Definition at line 304 of file CommandLine.py.

list CommandLine.Application.options = [] [static]

Reimplemented in pybench.PyBenchCmdline.

Definition at line 234 of file CommandLine.py.

Initial value:
[SwitchOption('-v',
                                   'generate verbose output'),
                      SwitchOption('-h',
                                   'show this help text'),
                      SwitchOption('--help',
                                   'show this help text'),
                      SwitchOption('--debug',
                                   'enable debugging'),
                      SwitchOption('--copyright',
                                   'show copyright'),
                      SwitchOption('--examples',
                                   'show examples of usage')]

Definition at line 237 of file CommandLine.py.

string CommandLine.Application.synopsis = '%(name)s [option] files...' [static]

Definition at line 274 of file CommandLine.py.

Definition at line 301 of file CommandLine.py.

Definition at line 295 of file CommandLine.py.

Definition at line 573 of file CommandLine.py.

Reimplemented in pybench.PyBenchCmdline.

Definition at line 277 of file CommandLine.py.


The documentation for this class was generated from the following file: