Next / Previous / Contents / Shipman's homepage

20. class Args(): Command line argument processor

The purpose of this class is to check for valid command line arguments, and issue an error message otherwise. The class is a singleton: after its first instantiation, each call to the constructor returns the same instance. The Singleton base class is borrowed from the Scanning objects for Python: Scan and Log.

noteweb
# - - - - -   c l a s s   A r g s

class Args(Singleton):
    '''Singleton class to represent command line arguments.

      Exports:
        Args():
          [ if the command line arguments are valid ->
              return the singleton Args() instance
              representing those arguments
            else ->
              sys.stderr  +:=  usage message
              stop execution ]
        .forceSwitch:
          [ if -f or --force was specified -> True
            else -> False ]
    '''

Overall processing and message generation is handled by Python's standard optparse module.

noteweb
    def __init__(self):
        '''Constructor.
        '''
        #-- 1 --
        # [ parser  :=  a new optparse.OptionParser instance
        #       representing the valid switches ]
        parser = optparse.OptionParser ( version="%s %s" %
            (PROGRAM_NAME, EXTERNAL_VERSION) )
        parser.add_option ( "-f", "--force",
            dest="force", default=False, action="store_true",
            help=("Rewrite all HTML files, not just those that are "
                  "out of date.") )

        #-- 2 --
        # [ if (parser likes the command line arguments) and
        #   (there are no positional arguments) ->
        #     options  :=  switch options
        #     argList  :=  positional arguments
        #   else ->
        #     sys.stderr  +:=  usage message
        #     stop execution ]
        options, argList = parser.parse_args()
        if len(argList) > 0:
            parser.error ( "This script takes no positional arguments." )

Finally, copy the value of the .force attribute of the returned options instance to the exported .forceSwitch attribute.

noteweb
        #-- 3 --
        self.forceSwitch = options.force