rpa-suite 1.4.5__py3-none-any.whl → 1.4.8__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- rpa_suite/__init__.py +4 -2
- rpa_suite/core/__init__.py +21 -4
- rpa_suite/core/browser.py +145 -8
- rpa_suite/core/clock.py +5 -1
- rpa_suite/core/date.py +6 -2
- rpa_suite/core/dir.py +6 -1
- rpa_suite/core/email.py +6 -4
- rpa_suite/core/file.py +12 -3
- rpa_suite/core/log.py +8 -1
- rpa_suite/core/parallel.py +193 -0
- rpa_suite/core/print.py +4 -2
- rpa_suite/core/regex.py +6 -1
- rpa_suite/core/validate.py +5 -2
- rpa_suite/functions/__create_ss_dir.py +6 -2
- rpa_suite/functions/_printer.py +3 -1
- rpa_suite/suite.py +25 -2
- rpa_suite/utils/__init__.py +1 -0
- rpa_suite/utils/system.py +10 -1
- {rpa_suite-1.4.5.dist-info → rpa_suite-1.4.8.dist-info}/METADATA +76 -39
- rpa_suite-1.4.8.dist-info/RECORD +24 -0
- rpa_suite/functions/__create_log_dir.py +0 -83
- rpa_suite/functions/_functions_logger.py +0 -96
- rpa_suite/functions/_logger.py +0 -113
- rpa_suite/functions/_variables.py +0 -10
- rpa_suite/functions/_variables_uru.py +0 -11
- rpa_suite-1.4.5.dist-info/RECORD +0 -28
- {rpa_suite-1.4.5.dist-info → rpa_suite-1.4.8.dist-info}/WHEEL +0 -0
- {rpa_suite-1.4.5.dist-info → rpa_suite-1.4.8.dist-info}/licenses/LICENSE +0 -0
- {rpa_suite-1.4.5.dist-info → rpa_suite-1.4.8.dist-info}/top_level.txt +0 -0
rpa_suite/suite.py
CHANGED
@@ -1,5 +1,6 @@
|
|
1
1
|
# rpa_suite/suite.py
|
2
2
|
|
3
|
+
# imports internal
|
3
4
|
from .core.clock import Clock
|
4
5
|
from .core.date import Date
|
5
6
|
from .core.email import Email
|
@@ -9,13 +10,20 @@ from .core.log import Log
|
|
9
10
|
from .core.print import Print
|
10
11
|
from .core.regex import Regex
|
11
12
|
from .core.validate import Validate
|
13
|
+
from .core.parallel import ParallelRunner
|
12
14
|
|
15
|
+
|
16
|
+
# imports external
|
13
17
|
from colorama import Fore
|
18
|
+
import pkg_resources
|
14
19
|
|
20
|
+
# imports third-party
|
15
21
|
import subprocess
|
16
22
|
import sys
|
17
23
|
import hashlib
|
18
24
|
|
25
|
+
|
26
|
+
|
19
27
|
# Windows bash colors
|
20
28
|
class Colors():
|
21
29
|
|
@@ -68,6 +76,7 @@ class Colors():
|
|
68
76
|
call_fn = f'{Fore.LIGHTMAGENTA_EX}'
|
69
77
|
retur_fn = f'{Fore.LIGHTYELLOW_EX}'
|
70
78
|
|
79
|
+
|
71
80
|
class Suite():
|
72
81
|
|
73
82
|
"""
|
@@ -138,15 +147,29 @@ class Suite():
|
|
138
147
|
printer: Print = Print()
|
139
148
|
regex: Regex = Regex()
|
140
149
|
validate: Validate = Validate()
|
141
|
-
|
150
|
+
Parallel: ParallelRunner = ParallelRunner
|
151
|
+
|
152
|
+
# On this case, we are importing the Browser class only if the selenium and webdriver_manager modules are installed.
|
153
|
+
# This is useful to avoid unnecessary imports and dependencies if the user does not need the Browser functionality.
|
154
|
+
import importlib.util
|
155
|
+
|
156
|
+
# from .browser import Browser
|
157
|
+
if importlib.util.find_spec("selenium") and importlib.util.find_spec("webdriver_manager"):
|
158
|
+
from .core.browser import Browser
|
159
|
+
browser: Browser = Browser
|
142
160
|
|
143
161
|
|
144
162
|
# VARIABLES INTERNAL
|
145
|
-
|
163
|
+
try:
|
164
|
+
__version__ = pkg_resources.get_distribution("rpa_suite").version
|
165
|
+
except Exception:
|
166
|
+
__version__ = 'unknown'
|
167
|
+
|
146
168
|
__id_hash__ = 'rpa_suite'
|
147
169
|
|
148
170
|
|
149
171
|
def __init__(self):
|
172
|
+
self.__id_hash__ = 'rpa_suite'
|
150
173
|
self.__id_hash__ = hashlib.sha256(self.__version__.encode()).hexdigest()
|
151
174
|
|
152
175
|
def success_print(self,
|
rpa_suite/utils/__init__.py
CHANGED
@@ -1,4 +1,5 @@
|
|
1
1
|
# rpa_suite/utils/__init__.py
|
2
|
+
|
2
3
|
"""
|
3
4
|
The utils module of the rpa-suite provides a collection of utility functions and classes that facilitate various tasks in process automation. It includes helper methods for logging, file handling, and other common operations that enhance the functionality and usability of the RPA Suite.
|
4
5
|
|
rpa_suite/utils/system.py
CHANGED
@@ -1,7 +1,14 @@
|
|
1
|
+
# rpa_suite/utils/system.py
|
2
|
+
|
3
|
+
# imports internal
|
1
4
|
from rpa_suite.functions._printer import error_print, success_print
|
5
|
+
|
6
|
+
# imports third-party
|
2
7
|
import sys, os
|
3
8
|
|
9
|
+
|
4
10
|
def set_importable_dir(display_message: bool = False):
|
11
|
+
|
5
12
|
"""
|
6
13
|
Sets the directory to be importable by appending it to the system path.
|
7
14
|
|
@@ -25,9 +32,11 @@ def set_importable_dir(display_message: bool = False):
|
|
25
32
|
----------
|
26
33
|
Nenhum
|
27
34
|
"""
|
35
|
+
|
28
36
|
try:
|
29
37
|
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
30
38
|
|
31
39
|
if display_message: success_print(f'Successfully set the directory for importation!')
|
40
|
+
|
32
41
|
except Exception as e:
|
33
|
-
error_print(f'An error occurred while executing the function: {set_importable_dir.__name__}! Error: {str(e)}.')
|
42
|
+
error_print(f'An error occurred while executing the function: {set_importable_dir.__name__}! Error: {str(e)}.')
|
@@ -1,6 +1,6 @@
|
|
1
1
|
Metadata-Version: 2.4
|
2
2
|
Name: rpa_suite
|
3
|
-
Version: 1.4.
|
3
|
+
Version: 1.4.8
|
4
4
|
Summary: Conjunto de ferramentas essenciais para Automação RPA com Python, que facilitam o dia a dia de desenvolvimento.
|
5
5
|
Author: Camilo Costa de Carvalho
|
6
6
|
Author-email: camilo.carvalho@triasoftware.com.br
|
@@ -25,6 +25,8 @@ Requires-Dist: loguru
|
|
25
25
|
Requires-Dist: typing
|
26
26
|
Requires-Dist: pillow
|
27
27
|
Requires-Dist: pyautogui
|
28
|
+
Requires-Dist: requests
|
29
|
+
Requires-Dist: setuptools
|
28
30
|
Dynamic: author
|
29
31
|
Dynamic: author-email
|
30
32
|
Dynamic: classifier
|
@@ -54,13 +56,16 @@ Dynamic: summary
|
|
54
56
|
|
55
57
|
## Sumário do conteudo
|
56
58
|
|
59
|
+
- [O que é?](#o-que-é)
|
60
|
+
- [Sumário do conteudo](#sumário-do-conteudo)
|
57
61
|
- [Destaque](#destaque)
|
58
62
|
- [Objetivo](#objetivo)
|
59
63
|
- [Instalação](#instalação)
|
60
64
|
- [Exemplo](#exemplo)
|
61
65
|
- [Dependências](#dependências)
|
62
66
|
- [Estrutura do módulo](#estrutura-do-módulo)
|
63
|
-
- [
|
67
|
+
- [Release](#release)
|
68
|
+
- [Notas da atualização: 1.4.8](#notas-da-atualização-148)
|
64
69
|
- [Mais Sobre](#mais-sobre)
|
65
70
|
|
66
71
|
## Destaque
|
@@ -94,17 +99,17 @@ ou no conda:
|
|
94
99
|
conda install -c conda-forge rpa-suite
|
95
100
|
```
|
96
101
|
|
97
|
-
Após instalação basta fazer a importação do modulo
|
102
|
+
Após instalação basta fazer a importação do modulo rpa que ja tera um objeto instanciado de ``suite``:
|
98
103
|
|
99
104
|
```python
|
100
|
-
from rpa_suite import
|
105
|
+
from rpa_suite import rpa
|
101
106
|
```
|
102
107
|
|
103
108
|
Feito isso já estará pronto para o uso:
|
104
109
|
|
105
110
|
```python
|
106
111
|
# function send mail by SMTP
|
107
|
-
rpa.send_mail(...)
|
112
|
+
rpa.email.send_mail(...)
|
108
113
|
```
|
109
114
|
|
110
115
|
> [!NOTE]
|
@@ -121,21 +126,24 @@ rpa.send_mail(...)
|
|
121
126
|
> Opcionalmente você pode querer desinstalar as libs que foram inclusas no projeto, sendo assim:
|
122
127
|
|
123
128
|
```python
|
124
|
-
>>> python -m pip uninstall loguru mail_validator colorama
|
129
|
+
>>> python -m pip uninstall loguru mail_validator colorama pillow pyautogui
|
125
130
|
```
|
126
131
|
|
127
132
|
## Exemplo
|
128
133
|
|
129
134
|
Do módulo principal, importe a suite. Ela retorna uma instância do Objeto de classe Rpa_suite, onde possui variáveis apontando para todas funções dos submódulos:
|
130
135
|
|
131
|
-
from rpa_suite import
|
136
|
+
from rpa_suite import rpa
|
132
137
|
|
133
|
-
#
|
134
|
-
rpa.
|
138
|
+
# Exemplo com função de execução em horario especifico
|
139
|
+
rpa.clock.exec_at_hour('13:53', my_function, param_a, param_b)
|
135
140
|
|
136
|
-
# Usando submódulo clock para aguardar 30
|
141
|
+
# Usando submódulo clock para aguardar 30(seg) para executar minha função
|
137
142
|
time = 30
|
138
|
-
rpa.wait_for_exec(time, my_function, param1, param2)
|
143
|
+
rpa.clock.wait_for_exec(time, my_function, param1, param2)
|
144
|
+
|
145
|
+
# Usando submódulo email para envio de email por smtp comum
|
146
|
+
rpa.email.send_smtp(...)
|
139
147
|
|
140
148
|
## Dependências
|
141
149
|
|
@@ -159,47 +167,80 @@ No caso da função de screenshot é necessario ter as libs 'pyautogui' 'pillow'
|
|
159
167
|
|
160
168
|
## Estrutura do módulo
|
161
169
|
|
162
|
-
O módulo principal do rpa-suite é dividido em categorias. Cada categoria contém módulos com funções destinadas a
|
163
|
-
|
164
|
-
! Divisao e nomes de funções precisam ser atualizadas nesta sessão de Estrutura do módulo !
|
170
|
+
O módulo principal do rpa-suite é dividido em categorias. Cada categoria contém módulos com funções destinadas a categoria:
|
165
171
|
|
166
172
|
- **rpa_suite**
|
173
|
+
|
167
174
|
- **clock**
|
168
|
-
- **
|
169
|
-
- **
|
175
|
+
- **exec_at_hour** - Função que executa uma função no horário especificado "xx:yy", permitindo agendamento de tarefas com precisão.
|
176
|
+
- **wait_for_exec** - Função que aguarda um tempo em segundos antes de executar a função passada como argumento.
|
177
|
+
- **exec_and_wait** - Função que executa uma função e, em seguida, aguarda um tempo em segundos antes de continuar.
|
178
|
+
|
170
179
|
- **date**
|
171
|
-
- **
|
180
|
+
- **get_hms** - Função que retorna hora, minuto e segundo formatados como strings.
|
181
|
+
- **get_dmy** - Função que retorna dia, mês e ano formatados como strings.
|
182
|
+
|
172
183
|
- **email**
|
173
|
-
- **
|
184
|
+
- **send_smtp** - Função para envio de emails via SMTP com suporte a anexos e mensagens HTML, configurável e personalizável.
|
185
|
+
|
174
186
|
- **file**
|
175
|
-
- **
|
176
|
-
- **
|
177
|
-
- **
|
178
|
-
- **
|
187
|
+
- **screen_shot** - Função para capturar screenshots, criando diretórios e arquivos com nomes e caminhos personalizáveis.
|
188
|
+
- **flag_create** - Função para criar arquivos de flag indicando execução de processos.
|
189
|
+
- **flag_delete** - Função para deletar arquivos de flag após a execução de processos.
|
190
|
+
- **count_files** - Função para contar arquivos em diretórios, com suporte a extensões específicas.
|
191
|
+
|
192
|
+
- **directory**
|
193
|
+
- **create_temp_dir** - Função para criar diretórios temporários com nomes e caminhos personalizáveis.
|
194
|
+
- **delete_temp_dir** - Função para deletar diretórios temporários, com opção de remover arquivos contidos.
|
195
|
+
|
179
196
|
- **log**
|
180
|
-
- **
|
181
|
-
- **
|
182
|
-
- **
|
197
|
+
- **config_logger** - Função para configurar logs com suporte a arquivos e streams, utilizando a biblioteca Loguru.
|
198
|
+
- **log_start_run_debug** - Função para registrar logs de início de execução em nível de depuração.
|
199
|
+
- **log_debug** - Função para registrar logs em nível de depuração.
|
200
|
+
- **log_info** - Função para registrar logs em nível informativo.
|
201
|
+
- **log_warning** - Função para registrar logs em nível de aviso.
|
202
|
+
- **log_error** - Função para registrar logs em nível de erro.
|
203
|
+
- **log_critical** - Função para registrar logs em nível crítico.
|
204
|
+
|
205
|
+
- **printer**
|
206
|
+
- **success_print** - Função para imprimir mensagens de sucesso com destaque em verde.
|
207
|
+
- **alert_print** - Função para imprimir mensagens de alerta com destaque em amarelo.
|
208
|
+
- **info_print** - Função para imprimir mensagens informativas com destaque em ciano.
|
209
|
+
- **error_print** - Função para imprimir mensagens de erro com destaque em vermelho.
|
183
210
|
- **regex**
|
184
|
-
- **
|
211
|
+
- **check_pattern_in_text** - Função para verificar a presença de padrões em textos, com suporte a case-sensitive.
|
212
|
+
|
185
213
|
- **validate**
|
186
|
-
- **
|
187
|
-
- **
|
214
|
+
- **emails** - Função para validar listas de emails, retornando listas de emails válidos e inválidos.
|
215
|
+
- **word** - Função para buscar palavras ou padrões específicos em textos, com suporte a contagem de ocorrências.
|
216
|
+
|
217
|
+
- **browser**
|
218
|
+
- **start_browser** - Função para iniciar o navegador Chrome com suporte a depuração remota.
|
219
|
+
- **find_ele** - Função para localizar elementos na página utilizando estratégias de localização do Selenium.
|
220
|
+
- **get** - Função para navegar para URLs específicas.
|
221
|
+
- **close_browser** - Função para fechar o navegador e encerrar processos relacionados.
|
222
|
+
|
223
|
+
- **parallel**
|
224
|
+
- **run** - Função para iniciar um processo em paralelo.
|
225
|
+
- **is_running** - Função para capturar o status atual do processo que esta rodando em paralelo.
|
226
|
+
- **get_result** - Função para coletar o retorno da execução em paralelo junto com resultado da função ou funções que foram enviadas a este processo com retorno em forma de dict.
|
227
|
+
- **terminate** - Função para finalizar o processo paralelo mantendo apenas o processo principal do seu código, também é chamada de forma automatica esta função ao final de um procesos paralelo ou no final da função "get_result".
|
188
228
|
|
189
229
|
## Release
|
190
230
|
|
191
|
-
Versão: **Beta 1.4.
|
231
|
+
Versão: **Beta 1.4.8**
|
192
232
|
|
193
233
|
Lançamento: *20/02/2024*
|
194
234
|
|
195
|
-
Última atualização: *
|
235
|
+
Última atualização: *12/04/2025*
|
196
236
|
|
197
237
|
Status: Em desenvolvimento.
|
198
238
|
|
199
|
-
### Notas da atualização: 1.4.
|
239
|
+
### Notas da atualização: 1.4.8
|
200
240
|
|
201
241
|
- Mudança dos submodulos para Objetos, agora Rpa_suite é um Objeto de Suite que compoe diversos sub-objetos separados pelas mesmas categorias anteriormente ja definidas
|
202
242
|
- Reformulada a arquitetura do projeto para melhor coeção e menos subpastas e arquivos, agora a estrutura é mais simples e de melhor manutenção contendo apenas uma pasta core para o nucleo de nossos modulos, e uma pasta utils com ferramentas utilitarias que vamos adicionar varias novidades
|
243
|
+
- Adicionado SubModulo Parallel com função dedicada a rodar um processo em paralelo com seu fluxo principal podendo recuperar o resultado da execução em paralelo a qualquer momento e setando timeout ou deixando o tempo indefinido para aguardar a resposta.
|
203
244
|
- Adicionado setor utils com funcionalidade de tornar o diretorio atual em um importavel relativo para o python
|
204
245
|
- Adicionado Automação de Navegadores! Sim estamos devendo esta feature a bastante tempo, porem estamos com a primeira versão disponivel, em breve teremos mais recursos e disponibilidade para outros navegadores, atualmente suporte apenas para *Chrome.*
|
205
246
|
- Mantemos o alerta! **get_dma** atualizada e **renomeada** para **get_dmy** para manter o padrão em ingles
|
@@ -212,13 +253,9 @@ Status: Em desenvolvimento.
|
|
212
253
|
## Mais Sobre
|
213
254
|
|
214
255
|
Para mais informações, visite nosso projeto no Github ou PyPi:
|
215
|
-
|
216
|
-
|
217
|
-
|
218
|
-
|
219
|
-
`<br>`
|
220
|
-
`<a href='https://pypi.org/project/rpa-suite/' target='_blank'>`
|
221
|
-
Ver projeto publicado no PyPI.
|
222
|
-
`</a>`
|
256
|
+
|
257
|
+
[Ver no GitHub](https://github.com/CamiloCCarvalho/rpa_suite)
|
258
|
+
|
259
|
+
[Ver projeto publicado no PyPI](https://pypi.org/project/rpa-suite/)
|
223
260
|
|
224
261
|
<hr>
|
@@ -0,0 +1,24 @@
|
|
1
|
+
rpa_suite/__init__.py,sha256=KO6GC2XbZUO56SAOgKxIkycHFEy6oeWPSswd8-B5IP4,2562
|
2
|
+
rpa_suite/suite.py,sha256=4aKwFsIz4YuDuKD41o2ws5bRkmt11uDblymCarYHHUw,11110
|
3
|
+
rpa_suite/core/__init__.py,sha256=27hq1brv83Kf89xtk-VVQx2etUWWBnVoZMgbgKI7Ac0,1678
|
4
|
+
rpa_suite/core/browser.py,sha256=XgUoOc6pcFwnSQxSlcOF0x8JjlUmj7gw3OvSJ_EoQns,14757
|
5
|
+
rpa_suite/core/clock.py,sha256=-ZEEaTYzwoYk9Bw1K6K1RN4s7O21uEhTg2hgBmdYLtQ,13880
|
6
|
+
rpa_suite/core/date.py,sha256=4T8_JKWBcYh4klQBAYx4RrmsKqz7uUb8wD5UtgCueeg,6629
|
7
|
+
rpa_suite/core/dir.py,sha256=sc_mJGrjo520cmNyC_HZo3YKEbORkBDfD3bCLaQ7U2o,9855
|
8
|
+
rpa_suite/core/email.py,sha256=CUqhW8-BF0XS7vFeZieQ13VywEg1TQZVoicEexSQCPE,8671
|
9
|
+
rpa_suite/core/file.py,sha256=9Psho6n9eqfLu3aA3XW43LzXefEJnAgIentFyopOpxQ,11623
|
10
|
+
rpa_suite/core/log.py,sha256=7VTPKXzVkWMg1W5bBO6BM3XDihKqNOcB4D-d6ytDbts,5631
|
11
|
+
rpa_suite/core/parallel.py,sha256=Pftz5cC-3jJLlprLjjSYadc6A9omBBmziCmeUcvNKh4,7668
|
12
|
+
rpa_suite/core/print.py,sha256=jhCNdid67dtVE6cCgRnWjqUrmsJcAr1hN38MHVupgfo,6423
|
13
|
+
rpa_suite/core/regex.py,sha256=gh3dlV29chepdoaWsl5yW9Db6MHQTGJeWstm0mD9zKU,3377
|
14
|
+
rpa_suite/core/validate.py,sha256=vKpl4u7f8CM30e_1rS6sqUqePy0ga51HHGn1cgent1o,11032
|
15
|
+
rpa_suite/functions/__create_ss_dir.py,sha256=FWLglWEYFCZUd_t-Peph1_ktfoH0fskkcfwxgU_pyks,3444
|
16
|
+
rpa_suite/functions/__init__.py,sha256=aa0jejVvnghufR50owKcKpmYit7XVAliyN9gn9JkdLE,33
|
17
|
+
rpa_suite/functions/_printer.py,sha256=51Xbqr0Ck7HHOrhJCxhMxdCKrF_kQ5AsKZN5SZQPwpk,3991
|
18
|
+
rpa_suite/utils/__init__.py,sha256=RQ-m9QNbaByek25moxx9ajpuxjPAEdjoMu69ReLBCWY,675
|
19
|
+
rpa_suite/utils/system.py,sha256=fQ9BAWxVETrFUeZJlfhN3cLzToU3XDQYqvDS9W0hWgY,1157
|
20
|
+
rpa_suite-1.4.8.dist-info/licenses/LICENSE,sha256=5D8PIbs31iGd9i1_MDNg4SzaQnp9sEIULALh2y3WyMI,1102
|
21
|
+
rpa_suite-1.4.8.dist-info/METADATA,sha256=N6Yo_DNSgM__jAR4X1SUULETkDQZRSnG-bcciOxkOXQ,12769
|
22
|
+
rpa_suite-1.4.8.dist-info/WHEEL,sha256=CmyFI0kx5cdEMTLiONQRbGQwjIoR1aIYB7eCAQ4KPJ0,91
|
23
|
+
rpa_suite-1.4.8.dist-info/top_level.txt,sha256=HYkDtg-kJNAr3F2XAIPyJ-QBbNhk7q6jrqsFt10lz4Y,10
|
24
|
+
rpa_suite-1.4.8.dist-info/RECORD,,
|
@@ -1,83 +0,0 @@
|
|
1
|
-
# /_create_log_dir.py
|
2
|
-
|
3
|
-
import os
|
4
|
-
from typing import Union
|
5
|
-
from rpa_suite.functions._printer import error_print, alert_print, success_print
|
6
|
-
|
7
|
-
|
8
|
-
def _create_log_dir(path_to_create: str = 'default', name_log_dir: str='logs') -> dict[str, Union[bool, str, None]]:
|
9
|
-
|
10
|
-
"""
|
11
|
-
Function responsible for creating a logger directory to work with files ``.log``. \n
|
12
|
-
|
13
|
-
Parameters:
|
14
|
-
----------
|
15
|
-
``path_to_create: str`` - should be a string with the full path pointing to the folder where the logger folder should be created, if it is empty the ``default`` value will be used which will create a folder in the current directory where the file containing this function was called.
|
16
|
-
|
17
|
-
``name_log_dir: str`` - should be a string representing the name of the logger directory to be created. If it is empty, the ``temp`` value will be used as the default directory name.
|
18
|
-
|
19
|
-
Return:
|
20
|
-
----------
|
21
|
-
>>> type:dict
|
22
|
-
* 'success': bool - represents case the action was performed successfully
|
23
|
-
* 'path_created': str - path of the directory that was created on the process
|
24
|
-
|
25
|
-
Description: pt-br
|
26
|
-
----------
|
27
|
-
Função responsavel por criar diretório de logger para trabalhar com arquivos de log. \n
|
28
|
-
|
29
|
-
Parametros:
|
30
|
-
----------
|
31
|
-
``path_to_create: str`` - deve ser uma string com o path completo apontando para a pasta onde deve ser criada a pasta temporaria, se estiver vazio sera usado valor ``default`` que criará pasta no diretório atual onde o arquivo contendo esta função foi chamada.
|
32
|
-
|
33
|
-
``name_log_dir: str`` - deve ser uma string representando o nome do diretório de logger a ser criado. Se estiver vazio, o valor ``temp`` será usado como o nome padrão do diretório.
|
34
|
-
|
35
|
-
Retorno:
|
36
|
-
----------
|
37
|
-
>>> type:dict
|
38
|
-
* 'success': bool - representa se ação foi realizada com sucesso
|
39
|
-
* 'path_created': str - path do diretório que foi criado no processo
|
40
|
-
"""
|
41
|
-
|
42
|
-
# Local Variables
|
43
|
-
result: dict = {
|
44
|
-
'success': bool,
|
45
|
-
'path_created': str,
|
46
|
-
}
|
47
|
-
|
48
|
-
try:
|
49
|
-
# by 'default', defines path to local script execution path
|
50
|
-
if path_to_create == 'default':
|
51
|
-
path_to_create: str = os.getcwd()
|
52
|
-
|
53
|
-
# Build path to new dir
|
54
|
-
full_path: str = os.path.join(path_to_create, name_log_dir)
|
55
|
-
|
56
|
-
# Create dir in this block
|
57
|
-
try:
|
58
|
-
|
59
|
-
# Successefully created
|
60
|
-
os.makedirs(full_path, exist_ok=False)
|
61
|
-
|
62
|
-
result['success'] = True
|
63
|
-
result['path_created'] = fr'{full_path}'
|
64
|
-
|
65
|
-
success_print(f"Diretório:'{full_path}' foi criado com sucesso.")
|
66
|
-
|
67
|
-
except FileExistsError:
|
68
|
-
result['success'] = False
|
69
|
-
result['path_created'] = full_path
|
70
|
-
# alert_print(f"Diretório:'{full_path}' já existe.")
|
71
|
-
|
72
|
-
except PermissionError:
|
73
|
-
result['success'] = False
|
74
|
-
result['path_created'] = None
|
75
|
-
alert_print(f"Permissão negada: não é possível criar o diretório '{full_path}'.")
|
76
|
-
|
77
|
-
except Exception as e:
|
78
|
-
result['success'] = False
|
79
|
-
result['path_created'] = None
|
80
|
-
error_print(f'Error capturing current path to create logger directory! Error: {str(e)}')
|
81
|
-
|
82
|
-
finally:
|
83
|
-
return result
|
@@ -1,96 +0,0 @@
|
|
1
|
-
# /_functions_logger.py
|
2
|
-
|
3
|
-
import logging
|
4
|
-
from ._logger import file_handler
|
5
|
-
from rpa_suite.functions._printer import error_print, success_print
|
6
|
-
|
7
|
-
|
8
|
-
def log_start_run_debug(msg_start_loggin: str) -> None: # represent start application
|
9
|
-
|
10
|
-
"""
|
11
|
-
Function responsable to generate ``start run log level debug``, in file and print on terminal the same log captured on this call.
|
12
|
-
"""
|
13
|
-
|
14
|
-
try:
|
15
|
-
global file_handler
|
16
|
-
file_handler.stream.write(f'\n{msg_start_loggin}\n')
|
17
|
-
success_print(f'{msg_start_loggin}')
|
18
|
-
|
19
|
-
except Exception as e:
|
20
|
-
error_print(f'Erro durante a função: {log_start_run_debug.__name__}! Error: {str(e)}')
|
21
|
-
|
22
|
-
|
23
|
-
def log_debug(msg) -> None:
|
24
|
-
|
25
|
-
"""
|
26
|
-
Function responsable to generate log level ``debug``, in file and print on terminal the same log captured on this call.
|
27
|
-
"""
|
28
|
-
|
29
|
-
try:
|
30
|
-
logging.debug(msg)
|
31
|
-
|
32
|
-
except Exception as e:
|
33
|
-
error_print(f'Erro durante a função: {log_debug.__name__}! Error: {str(e)}')
|
34
|
-
|
35
|
-
def log_info(msg) -> None:
|
36
|
-
|
37
|
-
"""
|
38
|
-
Function responsable to generate log level ``info``, in file and print on terminal the same log captured on this call.
|
39
|
-
"""
|
40
|
-
|
41
|
-
try:
|
42
|
-
logging.info(msg)
|
43
|
-
|
44
|
-
except Exception as e:
|
45
|
-
error_print(f'Erro durante a função: {log_debug.__name__}! Error: {str(e)}')
|
46
|
-
|
47
|
-
def log_info(msg) -> None:
|
48
|
-
|
49
|
-
"""
|
50
|
-
Function responsable to generate log level ``info``, in file and print on terminal the same log captured on this call.
|
51
|
-
"""
|
52
|
-
|
53
|
-
try:
|
54
|
-
logging.info(msg)
|
55
|
-
|
56
|
-
except Exception as e:
|
57
|
-
error_print(f'Erro durante a função: {log_info.__name__}! Error: {str(e)}')
|
58
|
-
|
59
|
-
|
60
|
-
def log_warning(msg) -> None:
|
61
|
-
|
62
|
-
"""
|
63
|
-
Function responsable to generate log level ``warning``, in file and print on terminal the same log captured on this call.
|
64
|
-
"""
|
65
|
-
|
66
|
-
try:
|
67
|
-
logging.warning(msg)
|
68
|
-
|
69
|
-
except Exception as e:
|
70
|
-
error_print(f'Erro durante a função: {log_warning.__name__}! Error: {str(e)}')
|
71
|
-
|
72
|
-
|
73
|
-
def log_error(msg) -> None:
|
74
|
-
|
75
|
-
"""
|
76
|
-
Function responsable to generate log level ``error``, in file and print on terminal the same log captured on this call.
|
77
|
-
"""
|
78
|
-
|
79
|
-
try:
|
80
|
-
logging.error(msg)
|
81
|
-
|
82
|
-
except Exception as e:
|
83
|
-
error_print(f'Erro durante a função: {log_error.__name__}! Error: {str(e)}')
|
84
|
-
|
85
|
-
|
86
|
-
def log_critical(msg) -> None:
|
87
|
-
|
88
|
-
"""
|
89
|
-
Function responsable to generate log level ``critical``, in file and print on terminal the same log captured on this call.
|
90
|
-
"""
|
91
|
-
|
92
|
-
try:
|
93
|
-
logging.critical(msg)
|
94
|
-
|
95
|
-
except Exception as e:
|
96
|
-
error_print(f'Erro durante a função: {log_critical.__name__}! Error: {str(e)}')
|
rpa_suite/functions/_logger.py
DELETED
@@ -1,113 +0,0 @@
|
|
1
|
-
# /_logger.py
|
2
|
-
|
3
|
-
import logging
|
4
|
-
from logging import DEBUG
|
5
|
-
from logging import FileHandler, StreamHandler, Filter
|
6
|
-
from colorlog import ColoredFormatter
|
7
|
-
from typing import Optional as Op
|
8
|
-
from ._variables import file_handler, stream_handler
|
9
|
-
from .__create_log_dir import _create_log_dir
|
10
|
-
from rpa_suite.functions._printer import error_print
|
11
|
-
|
12
|
-
|
13
|
-
class Filters(Filter):
|
14
|
-
|
15
|
-
word_filter: Op[list[str]]
|
16
|
-
|
17
|
-
def filter(self, record):
|
18
|
-
|
19
|
-
if len(self.word_filter) > 0:
|
20
|
-
|
21
|
-
for words in self.word_filter:
|
22
|
-
|
23
|
-
|
24
|
-
string_words: list[str] = [str(word) for word in words]
|
25
|
-
"""print(words)
|
26
|
-
print(type(words))
|
27
|
-
print(string_words)
|
28
|
-
print(type(string_words))
|
29
|
-
input()"""
|
30
|
-
for word in string_words:
|
31
|
-
if word in record.msg:
|
32
|
-
record.msg = 'Log Alterado devido a palavra Filtrada!'
|
33
|
-
return True
|
34
|
-
|
35
|
-
return True
|
36
|
-
|
37
|
-
|
38
|
-
def config_logger(name_app:str = 'Logger', path_dir:str = None, name_log_dir:str = None, name_file_log: str = 'log', use_default_path_and_name: bool = True, filter_words: list[str] = None) -> Op[FileHandler]:
|
39
|
-
|
40
|
-
"""
|
41
|
-
Function responsible for create a object logger with fileHandler and streamHandler
|
42
|
-
"""
|
43
|
-
|
44
|
-
global file_handler, stream_handler
|
45
|
-
|
46
|
-
try:
|
47
|
-
|
48
|
-
|
49
|
-
if not use_default_path_and_name:
|
50
|
-
result_tryed: dict = _create_log_dir(path_dir, name_log_dir)
|
51
|
-
path_dir = result_tryed['path_created']
|
52
|
-
else:
|
53
|
-
if path_dir == None and name_log_dir == None:
|
54
|
-
result_tryed: dict = _create_log_dir()
|
55
|
-
path_dir = result_tryed['path_created']
|
56
|
-
|
57
|
-
|
58
|
-
# configuração de objetos logger
|
59
|
-
file_handler = FileHandler(
|
60
|
-
filename=fr'{path_dir}\{name_file_log}.log',
|
61
|
-
mode='a',
|
62
|
-
encoding='utf-8'
|
63
|
-
)
|
64
|
-
stream_handler = StreamHandler()
|
65
|
-
|
66
|
-
# Crie um formatador
|
67
|
-
formatter = ColoredFormatter(
|
68
|
-
"%(log_color)s%(levelname)s ->%(reset)s %(log_color)s%(message)s%(reset)s",
|
69
|
-
datefmt=None,
|
70
|
-
reset=True,
|
71
|
-
log_colors={
|
72
|
-
'DEBUG': 'cyan',
|
73
|
-
'INFO': 'green',
|
74
|
-
'WARNING': 'yellow',
|
75
|
-
'ERROR': 'red',
|
76
|
-
'CRITICAL': 'red',
|
77
|
-
},
|
78
|
-
force_color=True
|
79
|
-
)
|
80
|
-
stream_handler.setFormatter(formatter)
|
81
|
-
|
82
|
-
# ATRIBUIÇÕES
|
83
|
-
new_filter: Op[Filters] = None
|
84
|
-
if filter_words is not None:
|
85
|
-
new_filter: Filters = Filters()
|
86
|
-
new_filter.word_filter = [filter_words]
|
87
|
-
|
88
|
-
if new_filter is not None:
|
89
|
-
file_handler.addFilter(new_filter)
|
90
|
-
|
91
|
-
file_handler.setLevel(DEBUG)
|
92
|
-
|
93
|
-
# Obtenha o logger
|
94
|
-
logger = logging.getLogger(__name__)
|
95
|
-
|
96
|
-
# Adicione o manipulador de stream ao logger
|
97
|
-
logger.addHandler(stream_handler)
|
98
|
-
|
99
|
-
# terminando de inplementar configuração para o logger
|
100
|
-
FORMAT = '%(levelname)s!%(asctime)s: %(message)s'
|
101
|
-
logging.basicConfig(
|
102
|
-
level=DEBUG, # level from stream_handler
|
103
|
-
#format='%(levelname)s - %(asctime)s - %(message)s',
|
104
|
-
format=FORMAT,
|
105
|
-
handlers=[file_handler, stream_handler],
|
106
|
-
datefmt='%d.%m.%y %H:%M',
|
107
|
-
)
|
108
|
-
return file_handler
|
109
|
-
|
110
|
-
except Exception as e:
|
111
|
-
|
112
|
-
error_print(f'Houve um erro durante a execução da função: {config_logger.__name__}! Error: {str(e)}.')
|
113
|
-
return None
|
@@ -1,10 +0,0 @@
|
|
1
|
-
# /_variables.py
|
2
|
-
|
3
|
-
from logging import FileHandler, StreamHandler
|
4
|
-
from typing import Optional
|
5
|
-
|
6
|
-
# Variável global para o manipulador de arquivo
|
7
|
-
file_handler: Optional[FileHandler] = None
|
8
|
-
|
9
|
-
# Variável global para o manipulador de stream stdout/stdin/buffer
|
10
|
-
stream_handler: Optional[StreamHandler] = None
|
@@ -1,11 +0,0 @@
|
|
1
|
-
# /_variables_uru.py
|
2
|
-
|
3
|
-
from loguru import logger
|
4
|
-
from typing import Optional
|
5
|
-
from typing import Any
|
6
|
-
|
7
|
-
# Variável global para o manipulador de arquivo
|
8
|
-
file_handler: Optional[str] = None
|
9
|
-
|
10
|
-
# Variável global para o manipulador de stream stdout/stdin/buffer
|
11
|
-
stream_handler: Optional[Any] = logger
|