rpa-suite 1.4.6__py3-none-any.whl → 1.4.9__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 +2 -0
- rpa_suite/core/__init__.py +2 -0
- rpa_suite/core/asyncrun.py +140 -0
- rpa_suite/core/browser.py +7 -4
- rpa_suite/core/clock.py +5 -1
- rpa_suite/core/date.py +7 -2
- rpa_suite/core/dir.py +6 -1
- rpa_suite/core/email.py +6 -4
- rpa_suite/core/file.py +10 -2
- rpa_suite/core/log.py +8 -1
- rpa_suite/core/parallel.py +313 -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 +27 -2
- rpa_suite/utils/__init__.py +1 -0
- rpa_suite/utils/system.py +10 -1
- {rpa_suite-1.4.6.dist-info → rpa_suite-1.4.9.dist-info}/METADATA +29 -4
- rpa_suite-1.4.9.dist-info/RECORD +25 -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.6.dist-info/RECORD +0 -28
- {rpa_suite-1.4.6.dist-info → rpa_suite-1.4.9.dist-info}/WHEEL +0 -0
- {rpa_suite-1.4.6.dist-info → rpa_suite-1.4.9.dist-info}/licenses/LICENSE +0 -0
- {rpa_suite-1.4.6.dist-info → rpa_suite-1.4.9.dist-info}/top_level.txt +0 -0
rpa_suite/__init__.py
CHANGED
@@ -1,4 +1,5 @@
|
|
1
1
|
# rpa_suite/__init__.py
|
2
|
+
|
2
3
|
"""
|
3
4
|
RPA Suite is a Python module that provides a set of tools for process automation.
|
4
5
|
|
@@ -59,5 +60,6 @@
|
|
59
60
|
``Browser``: Objeto de Automação de Navegadores (necessario Selenium e Webdriver_Manager)
|
60
61
|
"""
|
61
62
|
|
63
|
+
# allows importing the rpa_suite module without the package name
|
62
64
|
from .suite import rpa
|
63
65
|
rpa
|
rpa_suite/core/__init__.py
CHANGED
@@ -0,0 +1,140 @@
|
|
1
|
+
# rpa_suite/core/asyncrun.py
|
2
|
+
|
3
|
+
# imports third-party
|
4
|
+
from typing import Any, Callable, Dict, Optional, TypeVar, Generic
|
5
|
+
import asyncio
|
6
|
+
import time
|
7
|
+
import traceback
|
8
|
+
from functools import wraps
|
9
|
+
|
10
|
+
|
11
|
+
T = TypeVar('T')
|
12
|
+
|
13
|
+
|
14
|
+
class AsyncRunner(Generic[T]):
|
15
|
+
"""
|
16
|
+
Class to execute asynchronous functions while maintaining the main application flow.
|
17
|
+
|
18
|
+
Allows executing asynchronous functions and retrieving their results later.
|
19
|
+
Optimized for I/O bound operations (network, files, etc).
|
20
|
+
"""
|
21
|
+
|
22
|
+
def __init__(self):
|
23
|
+
"""Start AsyncRunner."""
|
24
|
+
self._task = None
|
25
|
+
self._start_time = None
|
26
|
+
self._result = {}
|
27
|
+
|
28
|
+
@staticmethod
|
29
|
+
def _to_async(func: Callable) -> Callable:
|
30
|
+
"""
|
31
|
+
Converts a synchronous function into an asynchronous one if necessary.
|
32
|
+
|
33
|
+
Args:
|
34
|
+
func: The function to be converted.
|
35
|
+
|
36
|
+
Returns:
|
37
|
+
A callable that is asynchronous.
|
38
|
+
"""
|
39
|
+
@wraps(func)
|
40
|
+
async def wrapper(*args, **kwargs):
|
41
|
+
if asyncio.iscoroutinefunction(func):
|
42
|
+
return await func(*args, **kwargs)
|
43
|
+
return await asyncio.to_thread(func, *args, **kwargs)
|
44
|
+
return wrapper
|
45
|
+
|
46
|
+
async def _execute_function(self, function, args, kwargs):
|
47
|
+
"""
|
48
|
+
Executes the function and manages results/errors.
|
49
|
+
|
50
|
+
Args:
|
51
|
+
function: The function to be executed.
|
52
|
+
args: Positional arguments for the function.
|
53
|
+
kwargs: Keyword arguments for the function.
|
54
|
+
"""
|
55
|
+
try:
|
56
|
+
async_func = self._to_async(function)
|
57
|
+
result = await async_func(*args, **kwargs)
|
58
|
+
|
59
|
+
self._result = {
|
60
|
+
'status': 'success',
|
61
|
+
'result': result,
|
62
|
+
'success': True
|
63
|
+
}
|
64
|
+
|
65
|
+
except Exception as e:
|
66
|
+
self._result = {
|
67
|
+
'status': 'error',
|
68
|
+
'error': str(e),
|
69
|
+
'traceback': traceback.format_exc(),
|
70
|
+
'success': False
|
71
|
+
}
|
72
|
+
|
73
|
+
def run(self, function: Callable[..., T], *args, **kwargs) -> 'AsyncRunner[T]':
|
74
|
+
"""
|
75
|
+
Starts the execution of the function asynchronously.
|
76
|
+
|
77
|
+
Args:
|
78
|
+
function: The function to be executed.
|
79
|
+
*args: Positional arguments for the function.
|
80
|
+
**kwargs: Keyword arguments for the function.
|
81
|
+
|
82
|
+
Returns:
|
83
|
+
self: Returns the instance itself.
|
84
|
+
"""
|
85
|
+
self._result.clear()
|
86
|
+
self._start_time = time.time()
|
87
|
+
|
88
|
+
# Creates and schedules the asynchronous task
|
89
|
+
loop = asyncio.get_event_loop()
|
90
|
+
self._task = loop.create_task(self._execute_function(function, args, kwargs))
|
91
|
+
|
92
|
+
return self
|
93
|
+
|
94
|
+
def is_running(self) -> bool:
|
95
|
+
"""
|
96
|
+
Checks if the task is still running.
|
97
|
+
|
98
|
+
Returns:
|
99
|
+
True if the task is running, False otherwise.
|
100
|
+
"""
|
101
|
+
return self._task is not None and not self._task.done()
|
102
|
+
|
103
|
+
async def get_result(self, timeout: Optional[float] = None) -> Dict[str, Any]:
|
104
|
+
"""
|
105
|
+
Retrieves the result of the asynchronous execution.
|
106
|
+
|
107
|
+
Args:
|
108
|
+
timeout: Maximum time (in seconds) to wait.
|
109
|
+
|
110
|
+
Returns:
|
111
|
+
A dictionary with the result or error information.
|
112
|
+
"""
|
113
|
+
if self._task is None:
|
114
|
+
return {
|
115
|
+
'success': False,
|
116
|
+
'error': 'No task has been started',
|
117
|
+
'execution_time': 0
|
118
|
+
}
|
119
|
+
|
120
|
+
try:
|
121
|
+
await asyncio.wait_for(self._task, timeout=timeout)
|
122
|
+
|
123
|
+
except asyncio.TimeoutError:
|
124
|
+
self._task.cancel()
|
125
|
+
return {
|
126
|
+
'success': False,
|
127
|
+
'error': f'Operation canceled due to timeout after {time.time() - self._start_time:.2f} seconds',
|
128
|
+
'execution_time': time.time() - self._start_time
|
129
|
+
}
|
130
|
+
|
131
|
+
result = dict(self._result)
|
132
|
+
result['execution_time'] = time.time() - self._start_time
|
133
|
+
return result
|
134
|
+
|
135
|
+
def cancel(self) -> None:
|
136
|
+
"""
|
137
|
+
Cancels the running task.
|
138
|
+
"""
|
139
|
+
if self.is_running():
|
140
|
+
self._task.cancel()
|
rpa_suite/core/browser.py
CHANGED
@@ -1,16 +1,19 @@
|
|
1
|
-
#
|
2
|
-
import os, requests
|
1
|
+
# rpa_suite/core/browser.py
|
3
2
|
|
4
|
-
# imports
|
3
|
+
# imports internal
|
5
4
|
from rpa_suite.functions._printer import error_print, alert_print, success_print
|
6
5
|
|
6
|
+
# imports external
|
7
7
|
from selenium import webdriver
|
8
8
|
from selenium.webdriver.common.by import By
|
9
9
|
from selenium.webdriver.chrome.options import Options
|
10
10
|
from selenium.webdriver.support.ui import WebDriverWait
|
11
11
|
from selenium.webdriver.support import expected_conditions as EC
|
12
12
|
from webdriver_manager.chrome import ChromeDriverManager
|
13
|
+
|
14
|
+
# imports third-party
|
13
15
|
from time import sleep
|
16
|
+
import os, requests
|
14
17
|
|
15
18
|
|
16
19
|
class Browser():
|
@@ -166,7 +169,7 @@ class Browser():
|
|
166
169
|
error_print(f'Erro ao iniciar navegador: {str(e)}.')
|
167
170
|
|
168
171
|
|
169
|
-
def find_ele(self, value, by=By.XPATH, timeout=12, display_message=True):
|
172
|
+
def find_ele(self, value: str, by:By=By.XPATH, timeout=12, display_message=True):
|
170
173
|
"""
|
171
174
|
Locate and return a web element on the page using the specified locator strategy.
|
172
175
|
Args:
|
rpa_suite/core/clock.py
CHANGED
@@ -1,8 +1,12 @@
|
|
1
|
+
# rpa_suite/core/clock.py
|
1
2
|
|
3
|
+
# imports internal
|
4
|
+
from rpa_suite.functions._printer import error_print, success_print
|
5
|
+
|
6
|
+
# imports third-party
|
2
7
|
import time
|
3
8
|
from typing import Callable, Any
|
4
9
|
from datetime import datetime as dt
|
5
|
-
from rpa_suite.functions._printer import error_print, success_print
|
6
10
|
from typing import Callable, Any
|
7
11
|
|
8
12
|
|
rpa_suite/core/date.py
CHANGED
@@ -1,11 +1,16 @@
|
|
1
|
-
# /date.py
|
1
|
+
# rpa_suite/core/date.py
|
2
2
|
|
3
|
+
# imports internal
|
4
|
+
from rpa_suite.functions._printer import error_print
|
5
|
+
|
6
|
+
# imports third-party
|
3
7
|
import datetime as dt
|
4
8
|
from typing import Optional as Op
|
5
9
|
from typing import Tuple
|
6
|
-
|
10
|
+
|
7
11
|
|
8
12
|
class Date():
|
13
|
+
|
9
14
|
"""
|
10
15
|
Class that provides utilities for date manipulation and formatting.
|
11
16
|
|
rpa_suite/core/dir.py
CHANGED
@@ -1,7 +1,12 @@
|
|
1
|
+
# rpa_suite/core/dir.py
|
1
2
|
|
3
|
+
# imports internal
|
4
|
+
from rpa_suite.functions._printer import error_print, alert_print, success_print
|
5
|
+
|
6
|
+
# imports third-party
|
2
7
|
import os, shutil
|
3
8
|
from typing import Union
|
4
|
-
|
9
|
+
|
5
10
|
|
6
11
|
|
7
12
|
class Directory():
|
rpa_suite/core/email.py
CHANGED
@@ -1,13 +1,15 @@
|
|
1
|
-
# /
|
1
|
+
# rpa_suite/core/email.py
|
2
2
|
|
3
|
-
|
3
|
+
# imports internal
|
4
|
+
from rpa_suite.functions._printer import alert_print, error_print, success_print
|
5
|
+
|
6
|
+
# imports third-party
|
7
|
+
import smtplib
|
4
8
|
from email.mime.image import MIMEImage
|
5
9
|
from email.mime.multipart import MIMEMultipart
|
6
10
|
from email.mime.text import MIMEText
|
7
11
|
from email.mime.base import MIMEBase
|
8
12
|
from email import encoders
|
9
|
-
from rpa_suite.functions._printer import alert_print, error_print, success_print
|
10
|
-
from rpa_suite.core.validate import email_validator
|
11
13
|
|
12
14
|
|
13
15
|
class Email():
|
rpa_suite/core/file.py
CHANGED
@@ -1,10 +1,18 @@
|
|
1
|
-
|
2
|
-
|
1
|
+
# rpa_suite/core/file.py
|
2
|
+
|
3
|
+
# imports internal
|
3
4
|
from rpa_suite.functions._printer import error_print, success_print, alert_print
|
4
5
|
from rpa_suite.functions.__create_ss_dir import __create_ss_dir as create_ss_dir
|
6
|
+
|
7
|
+
# imports external
|
5
8
|
from colorama import Fore
|
9
|
+
|
10
|
+
# imports third-party
|
11
|
+
import os, time
|
12
|
+
from datetime import datetime
|
6
13
|
from typing import Dict, List, Union
|
7
14
|
|
15
|
+
|
8
16
|
class File():
|
9
17
|
"""
|
10
18
|
Class that provides utilities for file management, including creation, deletion, and manipulation of files.
|
rpa_suite/core/log.py
CHANGED
@@ -1,6 +1,13 @@
|
|
1
|
-
|
1
|
+
# rpa_suite/core/log.py
|
2
|
+
|
3
|
+
# imports internal
|
2
4
|
from rpa_suite.functions._printer import error_print, alert_print, success_print
|
5
|
+
|
6
|
+
# imports external
|
3
7
|
from loguru import logger
|
8
|
+
|
9
|
+
# imports third-party
|
10
|
+
from typing import Optional as Op
|
4
11
|
import sys, os, inspect
|
5
12
|
|
6
13
|
|
@@ -0,0 +1,313 @@
|
|
1
|
+
# rpa_suite/core/parallel.py
|
2
|
+
|
3
|
+
# imports third-party
|
4
|
+
from multiprocessing import Process, Manager
|
5
|
+
from typing import Any, Callable, Dict, Optional, TypeVar, Generic
|
6
|
+
import time
|
7
|
+
import traceback
|
8
|
+
|
9
|
+
# Define a generic type for the function return
|
10
|
+
T = TypeVar('T')
|
11
|
+
|
12
|
+
|
13
|
+
class ParallelRunner(Generic[T]):
|
14
|
+
|
15
|
+
"""
|
16
|
+
Class to execute functions in parallel while maintaining the main application flow.
|
17
|
+
|
18
|
+
Allows starting a function in a separate process and retrieving its result later.
|
19
|
+
|
20
|
+
pt-br
|
21
|
+
------
|
22
|
+
Classe para executar funções em paralelo mantendo o fluxo principal da aplicação.
|
23
|
+
|
24
|
+
Permite iniciar uma função em um processo separado e obter seu resultado posteriormente.
|
25
|
+
"""
|
26
|
+
|
27
|
+
display_message = None
|
28
|
+
|
29
|
+
def __init__(self, display_message: bool = False):
|
30
|
+
"""
|
31
|
+
Initializes the ParallelRunner.
|
32
|
+
|
33
|
+
Args:
|
34
|
+
display_message (bool): If True, displays debug messages during execution.
|
35
|
+
|
36
|
+
pt-br
|
37
|
+
------
|
38
|
+
Inicializa o ParallelRunner.
|
39
|
+
|
40
|
+
Args:
|
41
|
+
display_message (bool): Se True, exibe mensagens de debug durante a execução.
|
42
|
+
"""
|
43
|
+
|
44
|
+
self._manager = Manager()
|
45
|
+
self._result_dict = self._manager.dict()
|
46
|
+
self._process = None
|
47
|
+
self._start_time = None
|
48
|
+
self.display_message = display_message
|
49
|
+
|
50
|
+
@staticmethod
|
51
|
+
def _execute_function(function, args, kwargs, result_dict):
|
52
|
+
"""
|
53
|
+
Static method that executes the target function and stores the result.
|
54
|
+
This function needs to be defined at the module level to be "picklable".
|
55
|
+
|
56
|
+
pt-br
|
57
|
+
------
|
58
|
+
Função estática que executa a função alvo e armazena o resultado.
|
59
|
+
Esta função precisa ser definida no nível do módulo para ser "picklable".
|
60
|
+
"""
|
61
|
+
try:
|
62
|
+
# Executa a função do usuário com os argumentos fornecidos
|
63
|
+
result = function(*args, **kwargs)
|
64
|
+
|
65
|
+
# Armazena o resultado no dicionário compartilhado
|
66
|
+
result_dict['status'] = 'success'
|
67
|
+
result_dict['result'] = result
|
68
|
+
|
69
|
+
# Para debug
|
70
|
+
#print(f"[Processo Filho] Resultado calculado: {result}")
|
71
|
+
#print(f"[Processo Filho] Dicionário de resultados: {dict(result_dict)}")
|
72
|
+
|
73
|
+
except Exception as e:
|
74
|
+
# Em caso de erro, armazena informações sobre o erro
|
75
|
+
result_dict['status'] = 'error'
|
76
|
+
result_dict['error'] = str(e)
|
77
|
+
result_dict['traceback'] = traceback.format_exc()
|
78
|
+
|
79
|
+
# Para debug
|
80
|
+
print(f"[Processo Filho] Erro ocorrido: {str(e)}")
|
81
|
+
|
82
|
+
@staticmethod
|
83
|
+
def _execute_function_w_disp_msg(function, args, kwargs, result_dict):
|
84
|
+
"""
|
85
|
+
Static method that executes the target function and stores the result.
|
86
|
+
This function needs to be defined at the module level to be "picklable".
|
87
|
+
|
88
|
+
pt-br
|
89
|
+
------
|
90
|
+
Função estática que executa a função alvo e armazena o resultado.
|
91
|
+
Esta função precisa ser definida no nível do módulo para ser "picklable".
|
92
|
+
"""
|
93
|
+
try:
|
94
|
+
# Executa a função do usuário com os argumentos fornecidos
|
95
|
+
result = function(*args, **kwargs)
|
96
|
+
|
97
|
+
# Armazena o resultado no dicionário compartilhado
|
98
|
+
result_dict['status'] = 'success'
|
99
|
+
result_dict['result'] = result
|
100
|
+
|
101
|
+
# Para debug
|
102
|
+
print(f"[Processo Filho] Resultado calculado: {result}")
|
103
|
+
print(f"[Processo Filho] Dicionário de resultados: {dict(result_dict)}")
|
104
|
+
|
105
|
+
except Exception as e:
|
106
|
+
# Em caso de erro, armazena informações sobre o erro
|
107
|
+
result_dict['status'] = 'error'
|
108
|
+
result_dict['error'] = str(e)
|
109
|
+
result_dict['traceback'] = traceback.format_exc()
|
110
|
+
|
111
|
+
# Para debug
|
112
|
+
print(f"[Processo Filho] Erro ocorrido: {str(e)}")
|
113
|
+
|
114
|
+
|
115
|
+
def run(self, function: Callable[..., T], *args, **kwargs) -> 'ParallelRunner[T]':
|
116
|
+
"""
|
117
|
+
Starts the execution of the function in a parallel process.
|
118
|
+
|
119
|
+
Args:
|
120
|
+
function: Function to be executed in parallel
|
121
|
+
*args: Positional arguments for the function
|
122
|
+
**kwargs: Keyword arguments for the function
|
123
|
+
|
124
|
+
Returns:
|
125
|
+
self: Returns the instance itself to allow chained calls
|
126
|
+
|
127
|
+
pt-br
|
128
|
+
------
|
129
|
+
Inicia a execução da função em um processo paralelo.
|
130
|
+
|
131
|
+
Args:
|
132
|
+
function: Função a ser executada em paralelo
|
133
|
+
*args: Argumentos posicionais para a função
|
134
|
+
**kwargs: Argumentos nomeados para a função
|
135
|
+
|
136
|
+
Returns:
|
137
|
+
self: Retorna a própria instância para permitir chamadas encadeadas
|
138
|
+
"""
|
139
|
+
# Limpar resultado anterior, se houver
|
140
|
+
if self._result_dict:
|
141
|
+
self._result_dict.clear()
|
142
|
+
|
143
|
+
# Configura valores iniciais no dicionário compartilhado
|
144
|
+
self._result_dict['status'] = 'running'
|
145
|
+
|
146
|
+
# Inicia o processo com a função auxiliar estática
|
147
|
+
if self.display_message:
|
148
|
+
self._process = Process(
|
149
|
+
target=ParallelRunner._execute_function_w_disp_msg,
|
150
|
+
args=(function, args, kwargs, self._result_dict)
|
151
|
+
)
|
152
|
+
else:
|
153
|
+
self._process = Process(
|
154
|
+
target=ParallelRunner._execute_function,
|
155
|
+
args=(function, args, kwargs, self._result_dict)
|
156
|
+
)
|
157
|
+
|
158
|
+
self._process.daemon = True # Processo filho termina quando o principal termina
|
159
|
+
self._process.start()
|
160
|
+
self._start_time = time.time()
|
161
|
+
|
162
|
+
return self
|
163
|
+
|
164
|
+
def is_running(self) -> bool:
|
165
|
+
"""
|
166
|
+
Checks if the process is still running.
|
167
|
+
|
168
|
+
Returns:
|
169
|
+
bool: True if the process is still running, False otherwise
|
170
|
+
|
171
|
+
pt-br
|
172
|
+
------
|
173
|
+
Verifica se o processo ainda está em execução.
|
174
|
+
|
175
|
+
Retorna:
|
176
|
+
bool: True se o processo ainda estiver em execução, False caso contrário
|
177
|
+
"""
|
178
|
+
if self._process is None:
|
179
|
+
return False
|
180
|
+
return self._process.is_alive()
|
181
|
+
|
182
|
+
def get_result(self, timeout: Optional[float] = 60, terminate_on_timeout: bool = True) -> Dict[str, Any]:
|
183
|
+
"""
|
184
|
+
Retrieves the result of the parallel execution.
|
185
|
+
|
186
|
+
Args:
|
187
|
+
timeout: Maximum time (in seconds) to wait for the process to finish.
|
188
|
+
None means wait indefinitely.
|
189
|
+
terminate_on_timeout: If True, terminates the process if the timeout is reached.
|
190
|
+
|
191
|
+
Returns:
|
192
|
+
- Dict containing:
|
193
|
+
- success: bool indicating if the operation was successful.
|
194
|
+
- result: result of the function (if successful).
|
195
|
+
- error: error message (if any).
|
196
|
+
- traceback: full stack trace (if an error occurred).
|
197
|
+
- execution_time: execution time in seconds.
|
198
|
+
- terminated: True if the process was terminated due to timeout.
|
199
|
+
|
200
|
+
pt-br
|
201
|
+
------
|
202
|
+
|
203
|
+
Recupera o resultado da execução paralela.
|
204
|
+
|
205
|
+
Args:
|
206
|
+
timeout: Tempo máximo (em segundos) para aguardar o término do processo.
|
207
|
+
None significa aguardar indefinidamente.
|
208
|
+
terminate_on_timeout: Se True, termina o processo se o tempo limite for atingido.
|
209
|
+
|
210
|
+
Retorna:
|
211
|
+
- Dicionário contendo:
|
212
|
+
- success: bool indicando se a operação foi bem-sucedida.
|
213
|
+
- result: resultado da função (se bem-sucedida).
|
214
|
+
- error: mensagem de erro (se houver).
|
215
|
+
- traceback: rastreamento completo da pilha (se ocorreu um erro).
|
216
|
+
- execution_time: tempo de execução em segundos.
|
217
|
+
- terminated: True se o processo foi terminado devido ao tempo limite.
|
218
|
+
"""
|
219
|
+
|
220
|
+
if self._process is None:
|
221
|
+
return {
|
222
|
+
'success': False,
|
223
|
+
'error': 'Nenhum processo foi iniciado',
|
224
|
+
'execution_time': 0,
|
225
|
+
'terminated': False
|
226
|
+
}
|
227
|
+
|
228
|
+
# Aguarda o processo terminar com tempo limite
|
229
|
+
self._process.join(timeout=timeout)
|
230
|
+
execution_time = time.time() - self._start_time
|
231
|
+
|
232
|
+
# Preparamos o dicionário de resposta
|
233
|
+
result = {
|
234
|
+
'execution_time': execution_time,
|
235
|
+
'terminated': False
|
236
|
+
}
|
237
|
+
|
238
|
+
# Debug - mostra o dicionário compartilhado
|
239
|
+
if self.display_message: print(f"[Processo Principal] Dicionário compartilhado: {dict(self._result_dict)}")
|
240
|
+
|
241
|
+
# Verifica se o processo terminou ou se atingiu o timeout
|
242
|
+
if self._process.is_alive():
|
243
|
+
if terminate_on_timeout:
|
244
|
+
self._process.terminate()
|
245
|
+
self._process.join(timeout=1) # Pequeno timeout para garantir que o processo termine
|
246
|
+
result['terminated'] = True
|
247
|
+
result['success'] = False
|
248
|
+
result['error'] = f'Operação cancelada por timeout após {execution_time:.2f} segundos'
|
249
|
+
else:
|
250
|
+
result['success'] = False
|
251
|
+
result['error'] = f'Operação ainda em execução após {execution_time:.2f} segundos'
|
252
|
+
else:
|
253
|
+
# Processo terminou normalmente - verificamos o status
|
254
|
+
status = self._result_dict.get('status', 'unknown')
|
255
|
+
|
256
|
+
if status == 'success':
|
257
|
+
result['success'] = True
|
258
|
+
# Garantimos que o resultado está sendo copiado corretamente
|
259
|
+
if 'result' in self._result_dict:
|
260
|
+
result['result'] = self._result_dict['result']
|
261
|
+
else:
|
262
|
+
result['success'] = False
|
263
|
+
result['error'] = 'Resultado não encontrado no dicionário compartilhado'
|
264
|
+
else:
|
265
|
+
result['success'] = False
|
266
|
+
result['error'] = self._result_dict.get('error', 'Erro desconhecido')
|
267
|
+
if 'traceback' in self._result_dict:
|
268
|
+
result['traceback'] = self._result_dict['traceback']
|
269
|
+
|
270
|
+
# Finaliza o Manager se o processo terminou e não estamos mais esperando resultado
|
271
|
+
if not self._process.is_alive() and (result.get('success', False) or result.get('terminated', False)):
|
272
|
+
self._cleanup()
|
273
|
+
|
274
|
+
return result
|
275
|
+
|
276
|
+
def terminate(self) -> None:
|
277
|
+
"""
|
278
|
+
Terminates the running process.
|
279
|
+
|
280
|
+
pt-br
|
281
|
+
------
|
282
|
+
Termina o processo em execução.
|
283
|
+
"""
|
284
|
+
if self._process and self._process.is_alive():
|
285
|
+
self._process.terminate()
|
286
|
+
self._process.join(timeout=1)
|
287
|
+
self._cleanup()
|
288
|
+
|
289
|
+
def _cleanup(self) -> None:
|
290
|
+
"""
|
291
|
+
Cleans up resources used by the process.
|
292
|
+
|
293
|
+
pt-br
|
294
|
+
------
|
295
|
+
Limpa os recursos utilizados pelo processo.
|
296
|
+
"""
|
297
|
+
if hasattr(self, '_manager') and self._manager is not None:
|
298
|
+
try:
|
299
|
+
self._manager.shutdown()
|
300
|
+
except Exception:
|
301
|
+
pass
|
302
|
+
self._manager = None
|
303
|
+
self._process = None
|
304
|
+
|
305
|
+
def __del__(self):
|
306
|
+
"""
|
307
|
+
Destructor of the class, ensures resources are released.
|
308
|
+
|
309
|
+
pt-br
|
310
|
+
------
|
311
|
+
Destrutor da classe, garante que recursos sejam liberados.
|
312
|
+
"""
|
313
|
+
self.terminate()
|
rpa_suite/core/print.py
CHANGED
@@ -1,8 +1,9 @@
|
|
1
|
+
# rpa_suite/core/print.py
|
1
2
|
|
2
|
-
#
|
3
|
-
|
3
|
+
# imports external
|
4
4
|
from colorama import Fore
|
5
5
|
|
6
|
+
|
6
7
|
# Windows bash colors
|
7
8
|
class Colors():
|
8
9
|
black = f'{Fore.BLACK}'
|
@@ -17,6 +18,7 @@ class Colors():
|
|
17
18
|
call_fn = f'{Fore.LIGHTMAGENTA_EX}'
|
18
19
|
retur_fn = f'{Fore.LIGHTYELLOW_EX}'
|
19
20
|
|
21
|
+
|
20
22
|
class Print():
|
21
23
|
|
22
24
|
"""
|
rpa_suite/core/regex.py
CHANGED
@@ -1,7 +1,12 @@
|
|
1
|
+
# rpa_suite/core/regex.py
|
1
2
|
|
2
|
-
|
3
|
+
# imports internal
|
3
4
|
from rpa_suite.functions._printer import error_print, success_print
|
4
5
|
|
6
|
+
# imports third-party
|
7
|
+
import re
|
8
|
+
|
9
|
+
|
5
10
|
class Regex():
|
6
11
|
"""
|
7
12
|
Class that provides utilities for working with regular expressions.
|
rpa_suite/core/validate.py
CHANGED
@@ -1,8 +1,12 @@
|
|
1
|
-
# /
|
1
|
+
# rpa_suite/functions/__create_ss_dir.py
|
2
2
|
|
3
|
+
# imports internal
|
4
|
+
from rpa_suite.functions._printer import error_print, alert_print, success_print
|
5
|
+
|
6
|
+
# imports third-party
|
3
7
|
import os
|
4
8
|
from typing import Union
|
5
|
-
|
9
|
+
|
6
10
|
|
7
11
|
|
8
12
|
def __create_ss_dir(path_to_create: str = 'default', name_ss_dir: str='screenshots') -> dict[str, Union[bool, str, None]]:
|
rpa_suite/functions/_printer.py
CHANGED
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,21 @@ 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
|
14
|
+
from .core.asyncrun import AsyncRunner
|
12
15
|
|
16
|
+
|
17
|
+
# imports external
|
13
18
|
from colorama import Fore
|
19
|
+
import pkg_resources
|
14
20
|
|
21
|
+
# imports third-party
|
15
22
|
import subprocess
|
16
23
|
import sys
|
17
24
|
import hashlib
|
18
25
|
|
26
|
+
|
27
|
+
|
19
28
|
# Windows bash colors
|
20
29
|
class Colors():
|
21
30
|
|
@@ -68,6 +77,7 @@ class Colors():
|
|
68
77
|
call_fn = f'{Fore.LIGHTMAGENTA_EX}'
|
69
78
|
retur_fn = f'{Fore.LIGHTYELLOW_EX}'
|
70
79
|
|
80
|
+
|
71
81
|
class Suite():
|
72
82
|
|
73
83
|
"""
|
@@ -138,15 +148,30 @@ class Suite():
|
|
138
148
|
printer: Print = Print()
|
139
149
|
regex: Regex = Regex()
|
140
150
|
validate: Validate = Validate()
|
141
|
-
|
151
|
+
Parallel: ParallelRunner = ParallelRunner
|
152
|
+
Asyn: AsyncRunner = AsyncRunner
|
153
|
+
|
154
|
+
# On this case, we are importing the Browser class only if the selenium and webdriver_manager modules are installed.
|
155
|
+
# This is useful to avoid unnecessary imports and dependencies if the user does not need the Browser functionality.
|
156
|
+
import importlib.util
|
157
|
+
|
158
|
+
# from .browser import Browser
|
159
|
+
if importlib.util.find_spec("selenium") and importlib.util.find_spec("webdriver_manager"):
|
160
|
+
from .core.browser import Browser
|
161
|
+
browser: Browser = Browser
|
142
162
|
|
143
163
|
|
144
164
|
# VARIABLES INTERNAL
|
145
|
-
|
165
|
+
try:
|
166
|
+
__version__ = pkg_resources.get_distribution("rpa_suite").version
|
167
|
+
except Exception:
|
168
|
+
__version__ = 'unknown'
|
169
|
+
|
146
170
|
__id_hash__ = 'rpa_suite'
|
147
171
|
|
148
172
|
|
149
173
|
def __init__(self):
|
174
|
+
self.__id_hash__ = 'rpa_suite'
|
150
175
|
self.__id_hash__ = hashlib.sha256(self.__version__.encode()).hexdigest()
|
151
176
|
|
152
177
|
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.9
|
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
|
@@ -26,6 +26,7 @@ Requires-Dist: typing
|
|
26
26
|
Requires-Dist: pillow
|
27
27
|
Requires-Dist: pyautogui
|
28
28
|
Requires-Dist: requests
|
29
|
+
Requires-Dist: setuptools
|
29
30
|
Dynamic: author
|
30
31
|
Dynamic: author-email
|
31
32
|
Dynamic: classifier
|
@@ -64,7 +65,7 @@ Dynamic: summary
|
|
64
65
|
- [Dependências](#dependências)
|
65
66
|
- [Estrutura do módulo](#estrutura-do-módulo)
|
66
67
|
- [Release](#release)
|
67
|
-
- [Notas da atualização: 1.4.
|
68
|
+
- [Notas da atualização: 1.4.9](#notas-da-atualização-149)
|
68
69
|
- [Mais Sobre](#mais-sobre)
|
69
70
|
|
70
71
|
## Destaque
|
@@ -155,6 +156,7 @@ No setup do nosso projeto já estão inclusas as dependências, só será necess
|
|
155
156
|
- pillow
|
156
157
|
- pyautogui
|
157
158
|
- typing
|
159
|
+
- setuptools
|
158
160
|
|
159
161
|
opcionalmente para automação de navegador:
|
160
162
|
|
@@ -169,23 +171,29 @@ No caso da função de screenshot é necessario ter as libs 'pyautogui' 'pillow'
|
|
169
171
|
O módulo principal do rpa-suite é dividido em categorias. Cada categoria contém módulos com funções destinadas a categoria:
|
170
172
|
|
171
173
|
- **rpa_suite**
|
174
|
+
|
172
175
|
- **clock**
|
173
176
|
- **exec_at_hour** - Função que executa uma função no horário especificado "xx:yy", permitindo agendamento de tarefas com precisão.
|
174
177
|
- **wait_for_exec** - Função que aguarda um tempo em segundos antes de executar a função passada como argumento.
|
175
178
|
- **exec_and_wait** - Função que executa uma função e, em seguida, aguarda um tempo em segundos antes de continuar.
|
179
|
+
|
176
180
|
- **date**
|
177
181
|
- **get_hms** - Função que retorna hora, minuto e segundo formatados como strings.
|
178
182
|
- **get_dmy** - Função que retorna dia, mês e ano formatados como strings.
|
183
|
+
|
179
184
|
- **email**
|
180
185
|
- **send_smtp** - Função para envio de emails via SMTP com suporte a anexos e mensagens HTML, configurável e personalizável.
|
186
|
+
|
181
187
|
- **file**
|
182
188
|
- **screen_shot** - Função para capturar screenshots, criando diretórios e arquivos com nomes e caminhos personalizáveis.
|
183
189
|
- **flag_create** - Função para criar arquivos de flag indicando execução de processos.
|
184
190
|
- **flag_delete** - Função para deletar arquivos de flag após a execução de processos.
|
185
191
|
- **count_files** - Função para contar arquivos em diretórios, com suporte a extensões específicas.
|
192
|
+
|
186
193
|
- **directory**
|
187
194
|
- **create_temp_dir** - Função para criar diretórios temporários com nomes e caminhos personalizáveis.
|
188
195
|
- **delete_temp_dir** - Função para deletar diretórios temporários, com opção de remover arquivos contidos.
|
196
|
+
|
189
197
|
- **log**
|
190
198
|
- **config_logger** - Função para configurar logs com suporte a arquivos e streams, utilizando a biblioteca Loguru.
|
191
199
|
- **log_start_run_debug** - Função para registrar logs de início de execução em nível de depuração.
|
@@ -194,6 +202,7 @@ O módulo principal do rpa-suite é dividido em categorias. Cada categoria cont
|
|
194
202
|
- **log_warning** - Função para registrar logs em nível de aviso.
|
195
203
|
- **log_error** - Função para registrar logs em nível de erro.
|
196
204
|
- **log_critical** - Função para registrar logs em nível crítico.
|
205
|
+
|
197
206
|
- **printer**
|
198
207
|
- **success_print** - Função para imprimir mensagens de sucesso com destaque em verde.
|
199
208
|
- **alert_print** - Função para imprimir mensagens de alerta com destaque em amarelo.
|
@@ -201,18 +210,32 @@ O módulo principal do rpa-suite é dividido em categorias. Cada categoria cont
|
|
201
210
|
- **error_print** - Função para imprimir mensagens de erro com destaque em vermelho.
|
202
211
|
- **regex**
|
203
212
|
- **check_pattern_in_text** - Função para verificar a presença de padrões em textos, com suporte a case-sensitive.
|
213
|
+
|
204
214
|
- **validate**
|
205
215
|
- **emails** - Função para validar listas de emails, retornando listas de emails válidos e inválidos.
|
206
216
|
- **word** - Função para buscar palavras ou padrões específicos em textos, com suporte a contagem de ocorrências.
|
217
|
+
|
207
218
|
- **browser**
|
208
219
|
- **start_browser** - Função para iniciar o navegador Chrome com suporte a depuração remota.
|
209
220
|
- **find_ele** - Função para localizar elementos na página utilizando estratégias de localização do Selenium.
|
210
221
|
- **get** - Função para navegar para URLs específicas.
|
211
222
|
- **close_browser** - Função para fechar o navegador e encerrar processos relacionados.
|
212
223
|
|
224
|
+
- **parallel**
|
225
|
+
- **run** - Função para iniciar um processo em paralelo.
|
226
|
+
- **is_running** - Função para capturar o status atual do processo que esta rodando em paralelo.
|
227
|
+
- **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.
|
228
|
+
- **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".
|
229
|
+
|
230
|
+
- **async**
|
231
|
+
- **run** - Função para iniciar a execução assíncrona de uma função mantendo o fluxo principal da aplicação.
|
232
|
+
- **is_running** - Função para verificar se a tarefa assíncrona ainda está em execução.
|
233
|
+
- **get_result** - Função para obter o resultado da execução assíncrona, incluindo tempo de execução e status, com suporte a timeout.
|
234
|
+
- **cancel** - Função para cancelar a tarefa assíncrona em execução.
|
235
|
+
|
213
236
|
## Release
|
214
237
|
|
215
|
-
Versão: **Beta 1.4.
|
238
|
+
Versão: **Beta 1.4.9**
|
216
239
|
|
217
240
|
Lançamento: *20/02/2024*
|
218
241
|
|
@@ -220,10 +243,12 @@ Lançamento: *20/02/2024*
|
|
220
243
|
|
221
244
|
Status: Em desenvolvimento.
|
222
245
|
|
223
|
-
### Notas da atualização: 1.4.
|
246
|
+
### Notas da atualização: 1.4.9
|
224
247
|
|
225
248
|
- 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
|
226
249
|
- 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
|
250
|
+
- 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.
|
251
|
+
- Adicionado SubModulo AsyncRunnner com função dedicada a facilitar uso de funções assincronas podendo recuperar seus resultados usando menos código, é um modulo simples porem poupa-nos tempo.
|
227
252
|
- Adicionado setor utils com funcionalidade de tornar o diretorio atual em um importavel relativo para o python
|
228
253
|
- 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.*
|
229
254
|
- Mantemos o alerta! **get_dma** atualizada e **renomeada** para **get_dmy** para manter o padrão em ingles
|
@@ -0,0 +1,25 @@
|
|
1
|
+
rpa_suite/__init__.py,sha256=KO6GC2XbZUO56SAOgKxIkycHFEy6oeWPSswd8-B5IP4,2562
|
2
|
+
rpa_suite/suite.py,sha256=1lsdFLz44gh7y3leOR5BCsx1dEKam5cm1g7l5RCFsYc,11187
|
3
|
+
rpa_suite/core/__init__.py,sha256=oGQiEtmgR9fBHgcAKYsl5eZsS2_SbRZnlhzOgRqXrAM,1713
|
4
|
+
rpa_suite/core/asyncrun.py,sha256=S5b-ueG4oJmupBZLsfYqcyTA5k5SaAi8j3KU8NnTOMg,4378
|
5
|
+
rpa_suite/core/browser.py,sha256=h1sMERkEw8y8zfQs2hdv2VbBNt3pQlVkMlkQOTKpaKQ,14755
|
6
|
+
rpa_suite/core/clock.py,sha256=-ZEEaTYzwoYk9Bw1K6K1RN4s7O21uEhTg2hgBmdYLtQ,13880
|
7
|
+
rpa_suite/core/date.py,sha256=0dqkP7zVjWeMmZA5xDZuvin97yYPMl1p0bCfLmtXdlM,6635
|
8
|
+
rpa_suite/core/dir.py,sha256=sc_mJGrjo520cmNyC_HZo3YKEbORkBDfD3bCLaQ7U2o,9855
|
9
|
+
rpa_suite/core/email.py,sha256=CUqhW8-BF0XS7vFeZieQ13VywEg1TQZVoicEexSQCPE,8671
|
10
|
+
rpa_suite/core/file.py,sha256=8eKlOSRptCYDJ-zRrHYK7tnmxR-JjQ55U47BRRdMGRE,11621
|
11
|
+
rpa_suite/core/log.py,sha256=7VTPKXzVkWMg1W5bBO6BM3XDihKqNOcB4D-d6ytDbts,5631
|
12
|
+
rpa_suite/core/parallel.py,sha256=p5jM7UwLWGYoYuQoUo659469nsuvy9QEkzVhXqu-GnU,11876
|
13
|
+
rpa_suite/core/print.py,sha256=jhCNdid67dtVE6cCgRnWjqUrmsJcAr1hN38MHVupgfo,6423
|
14
|
+
rpa_suite/core/regex.py,sha256=gh3dlV29chepdoaWsl5yW9Db6MHQTGJeWstm0mD9zKU,3377
|
15
|
+
rpa_suite/core/validate.py,sha256=vKpl4u7f8CM30e_1rS6sqUqePy0ga51HHGn1cgent1o,11032
|
16
|
+
rpa_suite/functions/__create_ss_dir.py,sha256=FWLglWEYFCZUd_t-Peph1_ktfoH0fskkcfwxgU_pyks,3444
|
17
|
+
rpa_suite/functions/__init__.py,sha256=aa0jejVvnghufR50owKcKpmYit7XVAliyN9gn9JkdLE,33
|
18
|
+
rpa_suite/functions/_printer.py,sha256=51Xbqr0Ck7HHOrhJCxhMxdCKrF_kQ5AsKZN5SZQPwpk,3991
|
19
|
+
rpa_suite/utils/__init__.py,sha256=RQ-m9QNbaByek25moxx9ajpuxjPAEdjoMu69ReLBCWY,675
|
20
|
+
rpa_suite/utils/system.py,sha256=fQ9BAWxVETrFUeZJlfhN3cLzToU3XDQYqvDS9W0hWgY,1157
|
21
|
+
rpa_suite-1.4.9.dist-info/licenses/LICENSE,sha256=5D8PIbs31iGd9i1_MDNg4SzaQnp9sEIULALh2y3WyMI,1102
|
22
|
+
rpa_suite-1.4.9.dist-info/METADATA,sha256=_Sb_Dl_nnF0kJYHsP0HGAQITOOWFvlndupMsQq9M47Y,13447
|
23
|
+
rpa_suite-1.4.9.dist-info/WHEEL,sha256=CmyFI0kx5cdEMTLiONQRbGQwjIoR1aIYB7eCAQ4KPJ0,91
|
24
|
+
rpa_suite-1.4.9.dist-info/top_level.txt,sha256=HYkDtg-kJNAr3F2XAIPyJ-QBbNhk7q6jrqsFt10lz4Y,10
|
25
|
+
rpa_suite-1.4.9.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
|
rpa_suite-1.4.6.dist-info/RECORD
DELETED
@@ -1,28 +0,0 @@
|
|
1
|
-
rpa_suite/__init__.py,sha256=A6Y1CmdmN9ADAgmvhS8FNXmLNP5fQuyUuZBTm9AKdQo,2494
|
2
|
-
rpa_suite/suite.py,sha256=pCbceWTf9WM_xt0GSf_k7Xnk4w_qHKS1hLscYqV5Ga0,10280
|
3
|
-
rpa_suite/core/__init__.py,sha256=TJ-WlsgWTVQ-jc-n66K5ZrqJJeHfI27jXytQVcVHN3M,1640
|
4
|
-
rpa_suite/core/browser.py,sha256=E-yD2LgwaDVOwUBs09BBXQVx5tLZ7DMFee8LYvgLClY,14682
|
5
|
-
rpa_suite/core/clock.py,sha256=1QnlOLs9YCRIq-tMFfk9OgaoicKtCL9sBzJmJmz9m_w,13808
|
6
|
-
rpa_suite/core/date.py,sha256=PBU999Acxiwoep029ElqKSzK6T4DrF3eIP-LB_J-BbM,6568
|
7
|
-
rpa_suite/core/dir.py,sha256=y6YDyRYQdf9Bj0z3Gs6ugNZ0tKWYgWdDI5R5BjjRIEY,9783
|
8
|
-
rpa_suite/core/email.py,sha256=kQJAc6Nb9y7jo-oBAo8X1EZS2y-_gTJRoRc9ylS04CE,8675
|
9
|
-
rpa_suite/core/file.py,sha256=rgvXqq_uV3D5wsioL4kTy0cbKv0bNO35alSVup6veHk,11524
|
10
|
-
rpa_suite/core/log.py,sha256=xCAoXLxnG2bVzXIafULvW45I4-ljo296E4auU1CppYY,5537
|
11
|
-
rpa_suite/core/print.py,sha256=tLHIKo6LDTrV91gWKvwlTrxb1idgx3EV_fIRkqtzWBM,6389
|
12
|
-
rpa_suite/core/regex.py,sha256=wsTxe8-baKul2Fv1-fycXZ-DVa5krhkc9qMkP04giGs,3303
|
13
|
-
rpa_suite/core/validate.py,sha256=0HnCUgT19LPBMhKxIV_hOAoixpqM7TAL9EkC0S56DFc,10976
|
14
|
-
rpa_suite/functions/__create_log_dir.py,sha256=-NjH3Mwv8Aa0EgZiD_TcdlSKbsoYl5EoYmPclFwjTKY,3325
|
15
|
-
rpa_suite/functions/__create_ss_dir.py,sha256=WMuDDTxM5xWudQjftC7xPr6y3IdiXjVK-GfxkQNIo4c,3377
|
16
|
-
rpa_suite/functions/__init__.py,sha256=aa0jejVvnghufR50owKcKpmYit7XVAliyN9gn9JkdLE,33
|
17
|
-
rpa_suite/functions/_functions_logger.py,sha256=hlYDEUsmmfwaPlY_YQeNQEFeT_mryHBqgBVyRdxge48,2703
|
18
|
-
rpa_suite/functions/_logger.py,sha256=gTYO9JlbX5_jDfu_4FTTajJw3_GotE2BHUbDDB1Hf5g,3643
|
19
|
-
rpa_suite/functions/_printer.py,sha256=r72zeobAi2baVbYgbfFH0h5-WMv4tSDGPNlcpZen7O0,3949
|
20
|
-
rpa_suite/functions/_variables.py,sha256=vCcktifFUriBQTyUaayZW8BlE8Gr7VP-tFbfomKOS5U,312
|
21
|
-
rpa_suite/functions/_variables_uru.py,sha256=xRqYp49l1fFNrHczOmJ6Pqw1PKIWs0f9kxlgvuYGYys,303
|
22
|
-
rpa_suite/utils/__init__.py,sha256=f0qiYRZ7VzBarp1yNj91V0UMZG9QY2mgDXEbWvNZDYs,673
|
23
|
-
rpa_suite/utils/system.py,sha256=JIONQutSbNBkQIATcN1wC0NUE4ILlgVZ-TOnuoMPxHI,1055
|
24
|
-
rpa_suite-1.4.6.dist-info/licenses/LICENSE,sha256=5D8PIbs31iGd9i1_MDNg4SzaQnp9sEIULALh2y3WyMI,1102
|
25
|
-
rpa_suite-1.4.6.dist-info/METADATA,sha256=N-wf425WMZNyO6PcTVXcHboPh97H4dZNaAgjfijqplI,11828
|
26
|
-
rpa_suite-1.4.6.dist-info/WHEEL,sha256=CmyFI0kx5cdEMTLiONQRbGQwjIoR1aIYB7eCAQ4KPJ0,91
|
27
|
-
rpa_suite-1.4.6.dist-info/top_level.txt,sha256=HYkDtg-kJNAr3F2XAIPyJ-QBbNhk7q6jrqsFt10lz4Y,10
|
28
|
-
rpa_suite-1.4.6.dist-info/RECORD,,
|
File without changes
|
File without changes
|
File without changes
|