def __init__(self, *Args, **kwargs): self.checks = Checks() self._slash = self.checks.directory_deliminator() self.script = inspect.getfile(inspect.currentframe()) self.scriptname = ntpath.basename(self.script).split('.')[0] self.script_path = os.getcwd() # Set logging defaults app_name = kwargs.pop("app_name", self.scriptname) logfile = kwargs.pop("logfile", 'syslog') log_level = kwargs.pop("log_level", 10) screendump = kwargs.pop("screendump", True) create_paths = kwargs.pop("create_paths", False) log.info( "Beginning execution: '" + str(self.scriptname) + "'. ", app_name=app_name, logfile=logfile, log_level=log_level, screendump=screendump, )
__author__ = "Mike Rightmire" __copyright__ = "BioCom Software" __license__ = "LGPLv3" __license_file__= "lgpl.txt" __version__ = "0.9.1.0" __maintainer__ = "Mike Rightmire" __email__ = "*****@*****.**" __status__ = "Development" ############################################################################## # from qrnote.errorhandler import handlertry # from qrnote.errorhandler import raisetry from BiocomCommon.checks import Checks checks = Checks() _slash = checks.directory_delimiter() def override_kw_vars(self, kwargs): for key in kwargs.keys(): self.config.__dict__[key] = kwargs[key] return True def set_mandatory_defaults(self, _dict): """ In the event the config file does not have the mandatory variables, and they are not passed in as __init__ variables, they can be set here. These defaults can be modified. The order of setting defaults should be: 1. config file 2. __init__ parameters 3. Here (_set_mandatory_defaults)
def __init__(self, *args, **kwargs): self.checks = Checks() self.config = ConfigHandler() self.source = kwargs.pop('source', None)
class XMLHandler(object): """""" def __init__(self, *args, **kwargs): self.checks = Checks() self.config = ConfigHandler() self.source = kwargs.pop('source', None) """ PROPERTIES =========================================================""" @property def source(self): try: return self._SOURCE except AttributeError as e: return None @source.setter def source(self, value): """""" if value is None: log.debug("xmlhandler.source has been set to None.") self._SOURCE = None self._TREE = None self._ROOT = None return _value = str(value) if not self.checks.pathExists(_value): err = ''.join([ "xmlhandler.source.setter: ", "The source path '", _value, "' appears invalid. " ]) raise ValueError(err) self._TREE = ET.parse(_value) self._ROOT = self._TREE.getroot() self._SOURCE = _value log.debug(''.join( ["xmlhandler.source has been set to '", _value, "'."])) @source.deleter def source(self): self._SOURCE = None self._TREE = None self._ROOT = None @property def tree(self): try: return self._TREE except AttributeError as e: return None @tree.setter def tree(self, value): err = ''.join([ "xmlhandler.tree.setter: The 'tree' parameter cannot be manually set. Please set 'source' value instead." ]) raise NotImplementedError(err) @tree.deleter def tree(self): del source @property def root(self): try: return self._ROOT except AttributeError as e: return None @root.setter def root(self, value): err = ''.join([ "xmlhandler.root.setter: The 'root' parameter cannot be manually set. Please set 'source' value instead." ]) raise NotImplementedError(err) @root.deleter def root(self): del source @property def elements(self): try: return self._ELEMENTS except (AttributeError, NameError) as e: self._ELEMENTS = [] return self._ELEMENTS @elements.setter def elements(self, value): """ value must be a string, in the format of an ElementTree findall statement. Currently, no string checks are performed. Screw up at your own risk. """ # For now, does no check on the value string...so we assume the user # knows what the hell s/he's doing. self._ELEMENTS = self.root.findall(value) @elements.deleter def elements(self): self._ELEMENTS = [] @property def element(self): try: return self._ELEMENT except (AttributeError, NameError) as e: self._ELEMENT = None return self._ELEMENT @element.setter def element(self, value): """ """ err = ''.join( [self.__class__.__name__, ".", inspect.stack()[0][3], ": "]) def _passed_element(value): self._ELEMENT = value def _passed_tuple(value): if ((len(value) < 2) or (len(value) > 3)): _err = ''.join([ err, "Tuple must contain 2 or 3 values in the format (attrib_name, attrib_value, number_of_matched_instance). " ]) raise ValueError(_err) # Get found instance number _end_count try: _end_count = value[2] except IndexError: _end_count = 1 # Search elements _count = 0 for elem in self.dump(): try: if elem.attrib[value[0]] == value[1]: # Check which numbered match this is _count += 1 # Increment match if _count == _end_count: self._ELEMENT = elem return # KeyError when there is no elem.attrib[value[0]] except KeyError: continue # If here, nothing got found, or the Nth (_count_end) match was not found self._ELEMENT = None return False """BEGIN""" # if isinstance(value, xml.etree.ElementTree.Element): # Doesnt work. I dont know why # Element passed in...just set if str(type(value)) == "<type 'Element'>": return _passed_element(value) # assumes first instance of elem.attrib[]'name' elif isinstance(value, str): return _passed_tuple(('name', value)) # Finds (elem-attrib-name, elem-attrib-value, number of found instance) elif isinstance(value, tuple): return _passed_tuple(value) # Invalid input else: err = ''.join([ err, "Value '", str(value), "' is not a valid object. ", "\n'value' must be a Name String, an ElementTree Element object, or a tupl containing a (attrib, value, instance) pair. " ]) raise ValueError(err) @element.deleter def element(self): self._ELEMENT = None """ PRIVATE METHODS ====================================================""" """ PUBLIC METHODS ====================================================""" @classmethod def isXMLHandler(self, XML): # Try to load the file as xml if isinstance(XML, XMLHandler): return XML else: # If source is not a valid xml file, this will error. try: return XMLHandler(source=XML) except Exception as e: stack = inspect.stack() _class = stack[1][0].f_locals["self"].__class__ err = ''.join([ _class, ".isXMLHandler:", "Parameter must be an XMLHandler object, or a full-path string to an XML file. (Value = '", str(XML), "'." ]) raise ValueError(err) def write(self, dest=None): """ :NAME: write([dest = String]) :PARAMETERS: dest = (OPTIONAL) The full file path to which the XML output will be written. If not supplied, the destination file will be the original source file (WARNING: THIS WILL OVERWRITE THE SOURCE FILE!) """ err = ''.join( [self.__class__.__name__, ".", inspect.stack()[0][3], ": "]) if dest is None: dest is self.source try: self.tree.write(dest, encoding='ISO-8859-1', xml_declaration=True) except Exception as e: msg = ''.join([ err, "An unknown error occurred trying to export XML. (", str(e), ")." ]) log.error(msg) return False msg = ''.join(["Tree successfully exported to '", dest, "'. "]) log.info(msg) return True def dump(self, _elem=None): """ :NAME: :RETURNS: A list of cElementTree Elements. """ if _elem is None: return self.root.getiterator() elif str(type(_elem)) == "<type 'Element'>": return _elem.getiterator() else: err = ''.join( [self.__class__.__name__, ".", inspect.stack()[0][3], ": "]) err = ''.join([err, "Value passed in is not a valid cElement"]) raise ValueError(err)
def __new__( cls, app_name='UNCHANGED', # DO NOT CHANGE FROM 'UNCHANGED' logfile='UNCHANGED', # DO NOT CHANGE FROM 'UNCHANGED' log_level='UNCHANGED', # DO NOT CHANGE FROM 'UNCHANGED' screendump='UNCHANGED', # DO NOT CHANGE FROM 'UNCHANGED' format='UNCHANGED', # DO NOT CHANGE FROM 'UNCHANGED' create_paths='UNCHANGED', # DO NOT CHANGE FROM 'UNCHANGED' migrate='UNCHANGED', # DO NOT CHANGE FROM 'UNCHANGED' instantiate=True # DO NOT CHANGE FROM True ): """ This is a singleton class. The __new__ method is called prior to instantiation with __init__. If there's already an instance of the class, the existing object is returned. If it doesn't exist, a new object is instantiated with the __init__. """ #============= FOR DEBUGGING =========================================== # try: #333 # print cls.instance,'============' # print datetime.datetime.now().time() # print cls.instance.create_time # except Exception as e: #333 # print 'No instance: ', str(e) #333 #======================================================================= # __init__ is called no matter what, so... # If there is NOT an instance, just create an instance # This WILL run __init__ # Do NOT set self.__exists here, since if _-exists == True, __init__ is # cancelled (it must still run at the first instantiation) if not hasattr(cls, 'instance'): if instantiate: # Create an instance cls.instance = super(SetLogger, cls).__new__(cls) cls.instance.checks = Checks() # SET INSTANCE DEFUALTS HERE ============================================= # These must be set or errors will arise. cls.instance._APP_NAME = 'loghandler' cls.instance._LOGFILE = False cls.instance._LOG_LEVEL = 10 cls.instance._SCREENDUMP = False cls.instance._FORMAT = '%(asctime)s - %(name)s - %(levelname)s - %(message)s' cls.instance._CREATE_PATHS = True cls.instance.instantiate = True cls.instance._MIGRATE = True cls.instance._FORMATTER = logging.Formatter( cls.instance.format) cls.instance._changed_flag = False cls.instance._changed_flag_message = '' return cls.instance else: return None # Else if an instance does exist, set a flag since # __init__is called, but flag halts completion (just returns) else: cls.instance.__exists = True return cls.instance
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. __author__ = "Mike Rightmire" __copyright__ = "BioCom Software" __license__ = "LGPLv3" __license_file__ = "lgpl.txt" __version__ = "0.9.1.0" __maintainer__ = "Mike Rightmire" __email__ = "*****@*****.**" __status__ = "Development" ############################################################################## from BiocomCommon.checks import Checks checks = Checks() from BiocomCommon.loghandler import log import re import subprocess import unicodedata def RunSubprocess(command, *args, **kwargs): """ """ verbose = kwargs.pop('verbose', False) # output = kwargs.pop('output', "string") # Depricated shell = kwargs.pop('shell', False) if shell: shell = True # Ensure is boolean