pyutil.py 5.72 KB
# -*- coding: UTF-8 -*-

# @def Função para obter data e hora atual do sistema
# @param string Formato de data e hora
# @return string Retorna data e hora do sistema no momento da chamada
def getTimeStamp(dtFrmt='%Y-%m-%d_%H.%M.%S.%f'):
    from datetime import datetime
    if (dtFrmt == '%Y-%m-%d_%H.%M.%S.%f'):
        # [:-3] Remove 3 casas decimais dos milisegundos (ms)
        return datetime.now().strftime(dtFrmt)[:-3]
    else:
        return datetime.now().strftime(dtFrmt)

# @def Função para gravar log dos eventos em arquivo
# @param string Mensagem a ser salva
# @param int indice do tipo de log 1: Debug, 2: Info, 3: Warn, 4: Error, 5: Critical
# @param String Caminho completo do arquivo de logs
# @param String Formato de tempo utilizado
def log(logMsg="", logLevel=2, logFile="events.log", dtFrmt='%Y-%m-%d %H:%M:%S'):
    import logging

    logLevelArray = ["", "DEBUG", "INFO", "WARNING", "ERROR", "CRITICAL" ]
    logLevel %= len(logLevelArray)
    print("[%s] log %s: %s" % (getTimeStamp(), logLevelArray[logLevel], logMsg))

    #logFormat='[%(asctime)s.%(msecs).03d] %(levelname)s: <User: %(name)s> <Module: %(module)s> <Function: %(funcName)s>: %(message)s'
    logFormat='[%(asctime)s.%(msecs).03d] %(levelname)s: %(message)s'

    if (logLevel == 1):
        logging.basicConfig(filename=logFile, datefmt=dtFrmt, format=logFormat, level=logging.DEBUG)
        logging.Formatter(fmt='%(asctime)s',datefmt='%Y/%m/%d,%H:%M:%S.%f')
        logging.debug(logMsg)

    elif (logLevel == 2):
        logging.basicConfig(filename=logFile, datefmt=dtFrmt, format=logFormat, level=logging.INFO)
        logging.Formatter(fmt='%(asctime)s',datefmt='%Y/%m/%d,%H:%M:%S.%f')
        logging.info(logMsg)

    elif (logLevel == 3):
        logging.basicConfig(filename=logFile, datefmt=dtFrmt, format=logFormat, level=logging.WARN)
        logging.Formatter(fmt='%(asctime)s',datefmt='%Y/%m/%d,%H:%M:%S.%f')
        logging.warn(logMsg)

    elif (logLevel == 4):
        logging.basicConfig(filename=logFile, datefmt=dtFrmt, format=logFormat, level=logging.ERROR)
        logging.Formatter(fmt='%(asctime)s',datefmt='%Y/%m/%d,%H:%M:%S.%f')
        logging.error(logMsg)

    elif (logLevel == 5):
        logging.basicConfig(filename=logFile, datefmt=dtFrmt, format=logFormat, level=logging.CRITICAL)
        logging.Formatter(fmt='%(asctime)s',datefmt='%Y/%m/%d,%H:%M:%S.%f')
        logging.critical(logMsg)

def test_log():
    msg = " This is a message "
    log(msg + "Debug", 1)
    log(msg + "Info", 2)
    log(msg + "Warn", 3)
    log(msg + "Error", 4)
    log(msg + "Critical", 5)

# test_log()

# @def Função para exibir exceção
# @param string deve ser passado: "__file__" para identificar em qual arquivo ocorreu a exceção
# @return int Retorna 1
def printStackTrace(fromFile):
    from sys import exc_info
    from os.path import basename
    error = "\n    File name: %s\n    Function name: %s\n    Line code: %s\n    Type exception: %s\n    Message: %s" % (
            basename(fromFile), # basename(exc_info()[2].tb_frame.f_code.co_filename),
            exc_info()[2].tb_frame.f_code.co_name,
            exc_info()[2].tb_lineno,
            exc_info()[0].__name__,
            exc_info()[1]
    )
    log(error, 4)
    return 1

# @def Função que verifica se um arquivo existe
# @param string filePath: Caminho do arquivo a ser checado
# @return bool Verdadeiro se o arquivo existir, Falso caso contrário
def file_exists(filePath):
    from os.path import isfile, exists
    if ((isfile(filePath) == 1) and (exists(filePath) == 1)):
        return True
    else:
        return False

# @def Função para renomear arquivo de video gerado pelo blender
# @see entrada: /temp/arquivo_video_0001-0250.mp4
# @see saida: /temp/arquivo_video.mp4
# @param string fileFullPath: Caminho do arquivo a ser renomeado
# @param bool useTimeStamp: Renomeia o arquivo de acordo com a data e hora do sistema
# @param bool overwrite: Sobreescreve o arquivo
# @return string Retorna o nome do arquivo renomeado
def file_rename(fileFullPath, useTimeStamp = False, overwrite = True):
    from shutil import move
    from os.path import abspath, basename, dirname, join, splitext
    if (file_exists(fileFullPath) == False):
        return ""
    filePath = dirname(abspath(fileFullPath))
    filename = basename(splitext(fileFullPath)[0])
    extension = splitext(fileFullPath)[1]
    filenameInv = ""
    isValidChar = False

    # Percorre o "filename" do final para o inicio copiando caracteres após o primeiro '_' encontrado
    for char in reversed(filename):
        if (isValidChar == True):
            filenameInv += char
        if (char == '_'):
            isValidChar = True
    try:

        # Inverte sequencia de caracteres que foi copiada
        filenameInv = filenameInv[::-1]

        if (useTimeStamp == True):
            # Recupera novo fullPath + nome do arquivo + data/hora + extensão
            newFilename = join(filePath, "%s_%s%s" % (filenameInv, getTimeStamp(), extension))
        else:
            # Recupera novo fullPath + nome do arquivo + extensão
            newFilename = join(filePath, "%s%s" % (filenameInv, extension))

            # Enumera o nome do arquivo caso o parametro "overwrite" seja "False" e o arquivo já exista
            if (overwrite == False):
                count = 0
                while (file_exists(newFilename) == True):
                    count += 1
                    # newFilename = join(filePath, "%s_%i%s" % (filenameInv, count, extension))
                    newFilename = join(filePath, "%s_%0.4i%s" % (filenameInv, count, extension))

        log("Rename: '%s' to: '%s'" %(fileFullPath, newFilename))
        move(fileFullPath, newFilename)
        return newFilename

    except Exception as e:
        printStackTrace(__file__)
        return ""