def VerifyPath(path, exitOnError=True): logger = SetLogger(__package__, stackNum=1) # log the caller logger.info('verifying path: {0} [{1}]'.format(path, type(path))) try: if isinstance(path, str): path = Path(path) path.resolve() pathExists = path.exists() except (Exception) as why: pathExists = False logger.error(str(why)) if pathExists: retPath = Path(path) logger.info('it exists.') else: retPath = None logger.error("it doesn't exists.") if exitOnError: LnExit(10, "{} doesn't exists".format(path)) return retPath
def getKeyboardInput(msg, validKeys='ENTER', exitKey='X', deepLevel=1, keySep="|", fDEBUG=False): logger = SetLogger(package=__name__) cPrint = LnColor() exitKeyUPP = exitKey.upper() if keySep in validKeys: validKeyLIST = validKeys.split(keySep) else: validKeyLIST = validKeys if keySep in exitKeyUPP: exitKeyLIST = exitKeyUPP.split(keySep) else: exitKeyLIST = [exitKeyUPP] print() if " uscita temporanea" in msg.lower(): if not 'ENTER' in exitKeyLIST: exitKeyLIST.append('ENTER') fDEBUG = True if fDEBUG: funcName = __name__.split('.')[-1] cPrint.Cyan(" {0} - exitKeyLIST....: {1}".format(funcName, exitKeyLIST), tab=4) cPrint.Cyan(" {0} - validKeyLIST...: {1}".format(funcName, validKeyLIST), tab=4) print() caller = _calledBy(deepLevel) msg = "<{CALLER}> - [{MSG} - ({VALKEY})] ({EXITKEY} to exit) ==> ".format(CALLER=caller, MSG=msg, VALKEY=validKeys, EXITKEY=exitKey) else: msg = "{0} [{1}] - ({2} to exit) ==> ".format(msg, validKeys, exitKey) try: while True: choice = input(msg).strip() # non mi accetta il colore choiceUPP = choice.upper() if fDEBUG: cPrint.Cyan("choice: [{0}]".format(choice)) if choice == '': # diamo priorità alla exit if "ENTER" in exitKeyLIST: sys.exit() elif "ENTER" in validKeys: return '' else: cPrint.Cyan('\n... please enter something\n') elif choiceUPP in exitKeyLIST: LnExit(9998, "Exiting on user request new.", printStack=True) elif choice in validKeyLIST: break else: cPrint.Cyan('\n... try again\n') except Exception as why: LnExit(8, "Error running program [{ME}]\n\n ....{WHY}\n".format(ME=sys.argv[0], WHY=why) ) return choice
def Exit(rcode, text=None, printStack=True, stackLevel=9, console=True): logger = SetLogger(package=__name__) C = LnColor() if text == None and rcode == 9999: textList = ['exiting for debbugging reason!'] elif text == None: textList = ['No error message passed'] elif isinstance(text, list): textList = text pass else: textList = text.split('\n') # ------------------------------- # - Display dell'Errore # ------------------------------- if rcode == 0: printColor = C.green logWrite = logger.debug elif rcode >9000: # uscite per debugging printColor = C.warning logWrite = logger.warning else: printColor = C.error logWrite = logger.error # ------------------------------- # - Display dello STACK # - http://blog.dscpl.com.au/2015/03/generating-full-stack-traces-for.html # ------------------------------- if console: C.printColored(color=printColor, text=" RCODE : {0}".format(rcode), tab=4) C.printColored(color=printColor, text=" TEXT Message: ", tab=4 ) for line in textList: C.printColored(color=printColor, text=line, tab=8) else: logWrite(" RCODE : {0}".format(rcode)) logWrite(" TEXT Message: " ) for line in textList: logWrite(' '*10 + "{0}".format(line)) if printStack: logWrite("EXIT STACK:") print() for i in reversed(list(range(1, stackLevel))): caller = _calledBy(i) if not 'index out of range' in caller: logWrite(" {0}".format(caller)) if console: C.printColored(color=printColor, text=caller, tab=8) sys.exit(rcode)
def setPath(pathName, pathValue, fMANDATORY=True, sepChar=';'): logger = SetLogger(__package__) newPATH = getenv(pathName) paths = pathValue.split(sepChar) for path in paths: path = LnVerifyPath(path, exitOnError=fMANDATORY) path = '{0};'.format(path) # add ; newPATH = newPATH.replace(path, '') # delete if exists newPATH = path + newPATH # add new one setVar(pathName, newPATH, fDEBUG=False)
def setPaths(dictVARS): logger = SetLogger(__package__) for pathName, pathValue in dictVARS.items(): if pathName.startswith('opt.'): fMANDATORY = False else: fMANDATORY = True # ------------------------------------------------- # - Setting PATH # ------------------------------------------------- setPath('PATH', pathValue, fMANDATORY=True, sepChar='\n')
def DirList(topDir, patternLIST=['*'], onlyDir=False, maxDeep=99): logger = SetLogger(package=__name__) # - eliminiamo i trailer BLANK patternLIST = [x.strip() for x in patternLIST if x] LISTA = [] for dirpath, dirs, files in os.walk(topDir, topdown=True): dirs[:] = [d for d in dirs if d != '.git'] # skip .git dirs depth = dirpath[len(topDir) + len(os.path.sep):].count(os.path.sep) if depth <= maxDeep: logger.debug('{DEPTH:02} - analyzing dir: {DIR}'.format( DEPTH=depth, DIR=dirpath)) for file_pattern in patternLIST: if onlyDir: # se vogliamo solo le directory if fnmatch.fnmatchcase(os.path.basename(dirpath), file_pattern): if not dirpath in LISTA: logger.debug("matched :{0}".format(dirpath)) LISTA.append(dirpath) else: LISTA.extend([ os.path.join(dirpath, filename) for filename in fnmatch.filter(files, file_pattern) ]) return LISTA
def setVars(dictVARS, fDEBUG=False): logger = SetLogger(__package__) # ------------------------------------------------- # - Setting delle variabili # ------------------------------------------------- for varName, varValue in dictVARS.items(): if varName.startswith('opt.'): varName = varName[4:] fMANDATORY = False else: fMANDATORY = True path = LnVerifyPath(varValue, exitOnError=fMANDATORY) setVar(varName, path, fDEBUG=fDEBUG)
def WriteTextFile(outFname, data=[], encoding='utf-8'): logger = SetLogger(package=__name__) logger.debug('writing file: {0}'.format(outFname)) logger.debug('number of lines to write: {0}'.format(len(data))) nLines = 0 newline = '\n' f = open(outFname, "w", encoding=encoding) for line in data: f.write('{0}{1}'.format(line, newline)) nLines += 1 f.close() return nLines
def StartProgram(textMsg, CMDList): logger = SetLogger(__package__) # -------------------------------------------------- # - Nella lista del comando potrebbero essere presenti # - path di file in formato PurePath... o simili # - e devo convertirli in str prima di lanciarli # -------------------------------------------------- logger.info(textMsg) myCMDList = [] for line in CMDList: if isinstance(line, (PureWindowsPath, WindowsPath)): line = str(line) myCMDList.append(line) logger.info(' ' + line) procID = Popen(myCMDList, shell=False, universal_newlines=True)
def readTextFile(inputFname, encoding='utf-8', strip=True): logger = SetLogger(package=__name__) row = [] logger.debug('reading file: {0}'.format(inputFname)) try: f = open(inputFname, "r", encoding=encoding) except (Exception) as why: gv.Ln.Exit(1, str(why), printStack=True) for line in f: if strip: line = line.strip() row.append(line) f.close() logger.debug('number of lines read: {0}'.format(len(row))) return row
def read(self, onlySection=None, returnOrderedDict=False, resolveEnvVars=False): logger = SetLogger(package=__package__) self._onlySection = onlySection self._returnOrderedDict = returnOrderedDict self._resolveEnvVars = resolveEnvVars configMain = self._configMain try: data = codecs.open(self._filename, "r", "utf8") self._configMain.readfp(data) except (Exception) as why: print("Errore nella lettura del file: {FILE} - {WHY}".format( FILE=self._filename, WHY=str(why))) sysExit(-1) # ------------------------------------------------------------------ # - per tutte le sezioni che sono extra facciamo il merge. # - Se Key-Val esistono esse sono rimpiazzate # ------------------------------------------------------------------ extraSections = self._extraSections for sectionName in self._extraSections: logger.info( 'adding Section: {SECTION}'.format(SECTION=sectionName)) logger.info(' data: {EXTRA}'.format( EXTRA=extraSections[sectionName])) extraSection = extraSections[sectionName] if not self._configMain.has_section(sectionName): logger.debug('creating Section: {0}'.format(sectionName)) self._configMain.add_section(sectionName) for key, val in extraSection.items(): logger.debug('adding on Section {0}:'.format(sectionName)) logger.debug(' key: {0}'.format(key)) logger.debug(' val: {0}'.format(val)) self._configMain.set(sectionName, key, val) # Parsing del file if type(self._configMain) in [configparser.ConfigParser]: self.dict = self._iniConfigAsDict() else: self.dict = self._configMain
def _iniConfigAsDict(self): logger = SetLogger(package=__package__) C = LnColor() """ Converts a ConfigParser object into a dictionary. The resulting dictionary has sections as keys which point to a dict of the sections options as key => value pairs. """ the_dict = collections.OrderedDict( {}) if self._returnOrderedDict else {} try: for section in self._configMain.sections(): # ----------------------------------------------------------------------- # - questo blocco serve per splittare eventuali section in cui il nome # - contiene un separatore (es. '.') ed interpretarli come subSections # ----------------------------------------------------------------------- if self._subSectionChar: myStr = section tempSep = '$@$@$' for sep in self._subSectionChar: myStr = myStr.replace(sep, tempSep) # subSection = section.split(self._subSectionChar) subSection = myStr.split(tempSep) else: subSection = [section] # una sola section currSECT = the_dict # top for sect in subSection: if not sect in currSECT: currSECT[sect] = collections.OrderedDict( {}) if self._returnOrderedDict else {} currSECT = currSECT[sect] # aggiorna pointer if self._fDEBUG: print() print('[{SECT}]'.format(SECT=section)) # for key, val in self._configMain.items(section): for key, val in self._configMain.items(section, raw=self._returnRAW): # --------------------------------------------------------------- # - cerchiamo di risolvere eventuali variabili di ambiente # - il nome dovrebbero essere solo i dispari della lista # --------------------------------------------------------------- if self._resolveEnvVars: envVars = val.split('%') for index, envVarName in enumerate(envVars): if index % 2: # print(envVarName) envVarValue = osGetEnv(envVarName) if envVarValue: val = val.replace( '%{}%'.format(envVarName), envVarValue) else: msg = 'nome della variabile di ambiente: [{VAR}] non trovato.'.format( VAR=envVarName) # C.Yellow(msg, tab=4) logger.warning(msg) if self._fDEBUG: C.Yellow(msg, tab=4) currSECT[key] = val if self._fDEBUG: print(' {KEY:<30} : {VAL}'.format(KEY=key, VAL=val)) except (configparser.InterpolationMissingOptionError) as why: print("\n" * 2) print("=" * 60) print("ERRORE nella validazione del file") print("-" * 60) print(str(why)) print("=" * 60) sysExit(-2) except (Exception) as why: print("\n" * 2) print("=" * 60) print("ERRORE nella validazione del file") print("-" * 60) print(str(why)) print("=" * 60) sysExit(-2) if self._onlySection: return the_dict[self._onlySection] else: return the_dict
def ExecRcode(command, timeout=None, EXECUTE=True, shell=False): logger = SetLogger(package=__name__) if isinstance(command, list): cmdLIST = command elif isinstance(command, str): cmdLIST = [x.strip() for x in command.split()] if shell: cmdLIST = ' '.join(cmdLIST) # Join command logger.debug('[dry-run: {DRYRUN}] - executing command "{0}"'.format( command, DRYRUN=not EXECUTE)) if EXECUTE: logger.info(' EXEC: {0}'.format(' '.join(cmdLIST))) import os # devnull = open(os.devnull, 'w') try: with open(os.devnull, "wb") as devnull: rCode = subprocess.call( cmdLIST, shell=shell, stdout=devnull, stderr=devnull, timeout=timeout) # ritorna <class 'bytes'> except subprocess.TimeoutExpired as why: msg = str(why) logger.error(msg) # rCode = 9 else: logger.info(' DRY-RUN: {0}'.format(command)) rCode = 0 if rCode: logger.error('rcode: {0}'.format(rCode)) return rCode ''' ALTRO metodo
def setVar(varName, varValue, fDEBUG=False): logger = SetLogger(__package__) msg = '{0:<20} : {1}'.format(varName, varValue) logger.info(msg) if fDEBUG: print(msg) environ[varName] = str(varValue)