]> Frank Brehm's Git Trees - my-stuff/fbrehm.git/commitdiff
Kopieren der eigenen Bibliotheken nach python/fbrehm/trunk
authorFrank Brehm <frank@brehm-online.com>
Mon, 3 Jan 2011 10:12:41 +0000 (10:12 +0000)
committerFrank Brehm <frank@brehm-online.com>
Mon, 3 Jan 2011 10:12:41 +0000 (10:12 +0000)
git-svn-id: http://svn.brehm-online.com/svn/my-stuff/python/fbrehm/trunk@175 ec8d2aa5-1599-4edb-8739-2b3a1bc399aa

src/__init__.py [new file with mode: 0755]
src/common/__init__.py [new file with mode: 0755]
src/common/getopt.py [new file with mode: 0755]
src/common/logging_obj.py [new file with mode: 0755]

diff --git a/src/__init__.py b/src/__init__.py
new file mode 100755 (executable)
index 0000000..3d21abb
--- /dev/null
@@ -0,0 +1,9 @@
+#!/usr/bin/python
+# -*- coding: utf-8 -*-
+'''
+@author: Frank Brehm
+@contact: frank@brehm-online.com
+@copyright: (c) 2010 - 2011 by Frank Brehm, Berlin
+@summary: All my own stuff
+'''
+# vim: fileencoding=utf-8 filetype=python ts=4
diff --git a/src/common/__init__.py b/src/common/__init__.py
new file mode 100755 (executable)
index 0000000..129b73b
--- /dev/null
@@ -0,0 +1,9 @@
+#!/usr/bin/python
+# -*- coding: utf-8 -*-
+'''
+@author: Frank Brehm
+@contact: frank@brehm-online.com
+@copyright: (c) 2010 - 2011 by Frank Brehm, Berlin
+@summary: All my own common stuff
+'''
+# vim: fileencoding=utf-8 filetype=python ts=4
diff --git a/src/common/getopt.py b/src/common/getopt.py
new file mode 100755 (executable)
index 0000000..b6772e4
--- /dev/null
@@ -0,0 +1,165 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+'''
+@author: Frank Brehm
+@contact: frank@brehm-online.com
+@copyright: (c) 2010-2011 by Frank Brehm, Berlin
+@license: GPL3
+@version: 0.0.2
+@summary: This module handle all getopt stuff
+'''
+
+__author__ = 'Frank Brehm <frank@brehm-online.com>'
+__copyright__ = '(C) 2010 by Frank Brehm, Berlin'
+__version__ = '0.0.2'
+
+import os
+import sys
+
+from optparse import OptionError
+from optparse import OptionParser
+from optparse import OptionConflictError
+
+class BaseOptParser(object):
+    '''
+    This is the base class for Option Parsing. All other getopts classes should
+    derived from this class. This class adds the default cmd named options like
+    '--test' and '--verbose'.
+    It implements also all callback functions/methods - so no class has to
+    write its own callback and every callback is reusable for every class.
+    @author: Robin Wittler / Frank Brehm
+    @contact: robin.wittler@profitbricks.com / frank@brehm-online.com
+    '''
+
+    #---------------------------------------------------------------------
+    def __init__( self, prog = '%prog',
+                        version = None,
+                        description = '',
+                        usage = 'Usage: %s [options]',
+                        test_option = False
+    ):
+        '''
+        Costructor.
+        @param prog: The name of the calling process (e.g. sys.argv[0])
+        @type prog: str
+        @param version: The version string to use
+        @type version: str
+        @param description: The Description the process should use
+        @type description: str
+        @param usage: An usage string fro the help screen, must have a '%s' for the program name
+        @type usage: str
+        @param test_option: should a test/simulate option be created? - default False
+        @type test_option: boolean
+        @return: None
+        '''
+
+        self.prog = prog
+        self.version = version
+        self.description = description
+        self.usage = usage %(prog)
+
+        self.options = None
+        self.args = None
+        self.__options_set = False
+        self.__action_set = None
+        self.parsed = False
+
+        self.parser = OptionParser(
+                prog        = self.prog,
+                version     = self.version,
+                description = self.description,
+                usage       = self.usage
+        )
+
+        if test_option:
+            self.addOption(
+                    '--simulate',
+                    '--test',
+                    '-T',
+                    default = False,
+                    action  = 'store_true',
+                    dest    = 'test',
+                    help    = 'set this do simulate commands'
+            )
+
+        self.addOption(
+                '--verbose',
+                '-v',
+                default = False,
+                action  = 'count',
+                dest    = 'verbose',
+                help    = 'set the verbosity level'
+        )
+
+    #----------------------------------------------------------------------
+    def getOpts(self):
+        '''
+        The baseimplentation of getOpts. It ensures that evry class
+        which derived from the base class have to call the 'addOption'
+        method first to add some options.
+        @return: None
+        '''
+        if not self.__options_set:
+            raise RuntimeError(
+                    'You must call addOption first.'
+            )
+        if not self.parsed:
+            self.options, self.args = self.parser.parse_args()
+            self.parsed = True
+
+    #----------------------------------------------------------------------
+    def addOption(self, *targs, **kwargs):
+        '''
+        This Method adds the options to the parser instance.
+        @param targs: The getopts cmd param names (e.g. '--help', '-h')
+        @type targs: tuple
+        @param kwargs: The named getopts options (e.g. 'dest', 'help',
+        'callback')
+        @type kwargs: dict
+        @return: None
+        @rtype: None
+        '''
+        self.parser.add_option(*targs, **kwargs)
+        if not self.__options_set:
+            self.__options_set = True
+
+    #----------------------------------------------------------------------
+    def setBaseOptionHelp( self, option_name, option_help ):
+        '''This method sets the help text of the named option.
+        @param option_name: The name of the option to change
+        @type option_name: str
+        @param option_help: The new option help text
+        @type option_help: str
+        @return: None
+        @rtype: None
+        '''
+
+        if not len(option_name):
+            raise SyntaxError( "empty option name given." )
+
+        as_long_option = True
+        if len(option_name) == 1: as_long_option = False
+
+        for option in self.parser.option_list:
+            opt_found = False
+            if as_long_option:
+                o = '--' + option_name
+                for opt in option._long_opts:
+                    if o == opt:
+                        opt_found = True
+                        break
+            else:
+                o = '-' + option_name
+                for opt in option._short_opts:
+                    if o == opt:
+                        opt_found = True
+                        break
+            if opt_found:
+                option.help = option_help
+                break
+
+    #---------------------------------------------------------------------
+
+
+
+# vim: fileencoding=utf-8 filetype=python ts=4 expandtab
diff --git a/src/common/logging_obj.py b/src/common/logging_obj.py
new file mode 100755 (executable)
index 0000000..95bf4d6
--- /dev/null
@@ -0,0 +1,96 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+'''
+@author: Frank Brehm
+@contact: frank@brehm-online.com
+@copyright: (c) 2010-2011 by Frank Brehm, Berlin
+@license: GPL3
+@version: 0.0.1
+@summary: This module includes the base logging object
+'''
+
+__author__ = 'Frank Brehm <frank@brehm-online.com>'
+__copyright__ = '(C) 2010 by Frank Brehm, Berlin'
+__contact__ = 'frank@brehm-online.com'
+__version__ = '0.0.1'
+__license__ = 'GPL3'
+
+import logging
+
+class LoggingObject(object):
+    """Base object with a verbose level and a logging facility.
+    """
+
+    #------------------------------------------------------
+    def __init__( self, verbose = 0, logger = None ):
+        """Constructor.
+        @param verbose: verbosity level (default: 0)
+        @type verbose: int
+        @param logger: a logger object for debugging a.s.o., will be created, if None
+        @type logger: a logging.Logger object or None
+        @return: None
+        @rtype: None
+        """
+
+        if not isinstance( verbose, int ):
+            raise Exception( "verbose is not an integer object" )
+
+        self.verbose = verbose
+
+        # Logging-Setup
+        if logger is None:
+            base_logger = self.init_base_logger()
+            self.logger = self.init_logger(base_logger)
+        elif isinstance( logger, logging.Logger ):
+            self.logger = self.init_logger( logger )
+        elif isinstance( logger, logging.LoggerAdapter ):
+            self.logger = logger
+            raise "self.logger is not a Logger or LoggerAdapter object"
+
+    #------------------------------------------------------
+    def init_logger( self, logger ):
+        """Initializes a LoggerAdapter object and returns it.
+        @param logger: a logger object for debugging a.s.o., will be created, if None
+        @type logger: a logging.Logger object or None
+        @return: None
+        @rtype: None
+        """
+
+        new_logger = logging.LoggerAdapter( logger, { 'class_name': self.__class__.__name__ } )
+
+        return new_logger
+
+    #------------------------------------------------------
+    def init_base_logger( self, logger_name = 'base_logger' ):
+        """Initializes a logger object and returns it, maybe overwritten.
+        @param logger_name: The name of the logging object
+        @type logger_name: str
+        @return: logger object
+        @rtype: logging.Logger
+        """
+
+        # Logging-Setup
+        loglevel = logging.WARNING
+        logformat = '%(levelname)s: %(message)s'
+        if self.verbose == 1:
+            loglevel = logging.INFO
+        elif self.verbose > 1:
+            loglevel = logging.DEBUG
+            logformat = '%(class_name)s - %(module)s.%(funcName)s(%(lineno)d) - %(levelname)s: %(message)s'
+
+        base_logger = logging.getLogger(logger_name)
+        base_logger.setLevel(loglevel)
+
+        ch = logging.StreamHandler()
+        ch.setLevel(loglevel)
+
+        formatter = logging.Formatter(logformat)
+        ch.setFormatter(formatter)
+
+        base_logger.addHandler(ch)
+
+        return base_logger
+
+#-------------------------------------------------------------------------------------------------
+
+# vim: fileencoding=utf-8 filetype=python ts=4 expandtab