pyutil.py
5.72 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
# -*- 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 ""