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/__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
|
|
@@ -26,7 +27,7 @@
|
|
26
27
|
``printer``: Functions for formatted output
|
27
28
|
``regex``: Operations with regular expressions
|
28
29
|
``validate``: Data validation functions
|
29
|
-
``Browser``: Object Browser automation functions
|
30
|
+
``Browser``: Object Browser automation functions (neeeds Selenium and Webdriver_Manager)
|
30
31
|
|
31
32
|
pt-br
|
32
33
|
-----
|
@@ -56,8 +57,9 @@
|
|
56
57
|
``printer``: Funções para output formatado
|
57
58
|
``regex``: Operações com expressões regulares
|
58
59
|
``validate``: Funções de validação de dados
|
59
|
-
``Browser``: Objeto de Automação de Navegadores
|
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
@@ -3,9 +3,12 @@
|
|
3
3
|
"""
|
4
4
|
The Core module is where we can import all Sub-Objects used by the rpa_suite module separately, categorized by their respective classes based on functionality. However, we can also use them through the main rpa object using the following syntax:
|
5
5
|
>>> from rpa_suite import rpa
|
6
|
-
>>> rpa.clock.wait_for_exec()
|
6
|
+
>>> rpa.clock.wait_for_exec(foo)
|
7
7
|
>>> rpa.file.screen_shot() ...
|
8
|
-
|
8
|
+
or
|
9
|
+
>>> from rpa_suite.core.clock import Clock
|
10
|
+
>>> clock = Clock()
|
11
|
+
>>> clock.wait_for_exec()
|
9
12
|
|
10
13
|
pt-br
|
11
14
|
----------
|
@@ -13,9 +16,13 @@ O módulo Core é de onde podemos importar todos os Sub-Objetos usados pelo mód
|
|
13
16
|
>>> from rpa_suite import rpa
|
14
17
|
>>> rpa.clock.wait_for_exec()
|
15
18
|
>>> rpa.file.screen_shot() ...
|
16
|
-
|
19
|
+
ou
|
20
|
+
>>> from rpa_suite.core.clock import Clock
|
21
|
+
>>> clock = Clock()
|
22
|
+
>>> clock.wait_for_exec(foo)
|
17
23
|
|
18
24
|
"""
|
25
|
+
|
19
26
|
from .clock import Clock
|
20
27
|
from .date import Date
|
21
28
|
from .dir import Directory
|
@@ -25,4 +32,14 @@ from .log import Log
|
|
25
32
|
from .print import Print
|
26
33
|
from .regex import Regex
|
27
34
|
from .validate import Validate
|
28
|
-
from .
|
35
|
+
from .parallel import ParallelRunner
|
36
|
+
|
37
|
+
|
38
|
+
|
39
|
+
# On this case, we are importing the Browser class only if the selenium and webdriver_manager modules are installed.
|
40
|
+
# This is useful to avoid unnecessary imports and dependencies if the user does not need the Browser functionality.
|
41
|
+
import importlib.util
|
42
|
+
|
43
|
+
# from .browser import Browser
|
44
|
+
if importlib.util.find_spec("selenium") and importlib.util.find_spec("webdriver_manager"):
|
45
|
+
from .browser import Browser
|
rpa_suite/core/browser.py
CHANGED
@@ -1,28 +1,92 @@
|
|
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
|
17
|
+
|
14
18
|
|
15
|
-
class Browser():
|
16
19
|
|
20
|
+
class Browser():
|
21
|
+
|
17
22
|
"""
|
18
|
-
|
23
|
+
Browser Object for Automation (Work in Progress)
|
24
|
+
This class provides an interface for automating browser interactions using
|
25
|
+
Google Chrome with a debugging port. It includes methods for starting,
|
26
|
+
configuring, navigating, and interacting with the browser. The implementation
|
27
|
+
is still under development and may require further enhancements.
|
28
|
+
|
29
|
+
Attributes:
|
30
|
+
driver: The WebDriver instance used to control the browser.
|
31
|
+
port (int): The debugging port used to connect to the browser. Default is 9393.
|
32
|
+
path_driver (str): The path to the ChromeDriver executable.
|
33
|
+
|
34
|
+
Methods:
|
35
|
+
__init__(port: int = 9393, close_all_chrome_on_this_port: bool = False):
|
36
|
+
Initializes the Browser object with the specified debugging port and
|
37
|
+
optionally closes all Chrome instances running on the same port.
|
38
|
+
configure_browser() -> None:
|
39
|
+
Configures the browser with debugging options and initializes the WebDriver.
|
40
|
+
start_browser(close_chrome_on_this_port: bool = True, display_message: bool = False):
|
41
|
+
Starts the Chrome browser with the specified debugging port and initializes
|
42
|
+
the WebDriver.
|
43
|
+
find_ele(value, by=By.XPATH, timeout=12, display_message=True):
|
44
|
+
Finds a single element on the page using the specified locator strategy.
|
45
|
+
get(url: str, display_message: bool = False):
|
46
|
+
Navigates the browser to the specified URL.
|
47
|
+
_close_all_chrome():
|
48
|
+
Closes all Chrome processes forcefully.
|
49
|
+
close_browser(display_message: bool = False):
|
50
|
+
Closes the browser instance and terminates the associated Chrome processes.
|
51
|
+
|
52
|
+
pt-br
|
53
|
+
----------
|
54
|
+
Objeto Browser para Automação (Em Desenvolvimento)
|
55
|
+
Esta classe fornece uma interface para automação de interações com o navegador
|
56
|
+
Google Chrome utilizando uma porta de depuração. Inclui métodos para iniciar,
|
57
|
+
configurar, navegar e interagir com o navegador. A implementação ainda está em
|
58
|
+
desenvolvimento e pode requerer melhorias adicionais.
|
59
|
+
|
60
|
+
Atributos:
|
61
|
+
driver: A instância do WebDriver usada para controlar o navegador.
|
62
|
+
port (int): A porta de depuração usada para conectar ao navegador. O padrão é 9393.
|
63
|
+
path_driver (str): O caminho para o executável do ChromeDriver.
|
64
|
+
|
65
|
+
Métodos:
|
66
|
+
__init__(port: int = 9393, close_all_chrome_on_this_port: bool = False):
|
67
|
+
Inicializa o objeto Browser com a porta de depuração especificada e,
|
68
|
+
opcionalmente, fecha todas as instâncias do Chrome que estão sendo executadas
|
69
|
+
na mesma porta.
|
70
|
+
configure_browser() -> None:
|
71
|
+
Configura o navegador com opções de depuração e inicializa o WebDriver.
|
72
|
+
start_browser(close_chrome_on_this_port: bool = True, display_message: bool = False):
|
73
|
+
Inicia o navegador Chrome com a porta de depuração especificada e inicializa
|
74
|
+
o WebDriver.
|
75
|
+
find_ele(value, by=By.XPATH, timeout=12, display_message=True):
|
76
|
+
Localiza um único elemento na página usando a estratégia de localização especificada.
|
77
|
+
get(url: str, display_message: bool = False):
|
78
|
+
Navega o navegador para a URL especificada.
|
79
|
+
_close_all_chrome():
|
80
|
+
Fecha todos os processos do Chrome de forma forçada.
|
81
|
+
close_browser(display_message: bool = False):
|
82
|
+
Fecha a instância do navegador e termina os processos associados do Chrome.
|
19
83
|
"""
|
20
84
|
|
21
85
|
driver: None
|
22
86
|
port: int = None
|
23
87
|
path_driver = None
|
24
88
|
|
25
|
-
def __init__(self, port: int = 9393, close_all_chrome_on_this_port: bool =
|
89
|
+
def __init__(self, port: int = 9393, close_all_chrome_on_this_port: bool = False):
|
26
90
|
self.port = port
|
27
91
|
self.path_driver = ChromeDriverManager().install()
|
28
92
|
|
@@ -30,6 +94,15 @@ class Browser():
|
|
30
94
|
...
|
31
95
|
|
32
96
|
def configure_browser(self) -> None:
|
97
|
+
"""
|
98
|
+
Configures the browser instance with specified options and initializes the WebDriver.
|
99
|
+
This method sets up the browser with debugging options, maximized window, and disables notifications.
|
100
|
+
It also verifies the existence of the ChromeDriver executable at the specified path before creating
|
101
|
+
the WebDriver instance.
|
102
|
+
Raises:
|
103
|
+
FileNotFoundError: If the specified path to the ChromeDriver executable does not exist.
|
104
|
+
Exception: For any other errors encountered during the browser configuration process.
|
105
|
+
"""
|
33
106
|
|
34
107
|
try:
|
35
108
|
# Use the absolute path from comment
|
@@ -57,6 +130,20 @@ class Browser():
|
|
57
130
|
error_print(f'Erro durante a função: {self.configure_browser.__name__}! Error: {str(e)}.')
|
58
131
|
|
59
132
|
def start_browser(self, close_chrome_on_this_port: bool = True, display_message: bool = False):
|
133
|
+
"""
|
134
|
+
Starts a Chrome browser instance with remote debugging enabled.
|
135
|
+
Args:
|
136
|
+
close_chrome_on_this_port (bool): If True, closes any existing Chrome instance using the specified debugging port before starting a new one. Defaults to True.
|
137
|
+
display_message (bool): If True, displays a success message upon successfully starting the browser. Defaults to False.
|
138
|
+
Raises:
|
139
|
+
Exception: If an error occurs while starting the browser or connecting to the debugging port.
|
140
|
+
Behavior:
|
141
|
+
- Closes any existing Chrome instance on the specified debugging port if `close_chrome_on_this_port` is True.
|
142
|
+
- Launches Chrome with the specified debugging port and user data directory.
|
143
|
+
- Waits until Chrome is fully initialized and accessible via the debugging port.
|
144
|
+
- Configures the browser instance using the `configure_browser` method.
|
145
|
+
- Optionally displays a success message if `display_message` is True.
|
146
|
+
"""
|
60
147
|
|
61
148
|
try:
|
62
149
|
if close_chrome_on_this_port: self.close_browser()
|
@@ -83,7 +170,24 @@ class Browser():
|
|
83
170
|
error_print(f'Erro ao iniciar navegador: {str(e)}.')
|
84
171
|
|
85
172
|
|
86
|
-
def find_ele(self, value, by=By.XPATH, timeout=12, display_message=True):
|
173
|
+
def find_ele(self, value: str, by:By=By.XPATH, timeout=12, display_message=True):
|
174
|
+
"""
|
175
|
+
Locate and return a web element on the page using the specified locator strategy.
|
176
|
+
Args:
|
177
|
+
value (str): The locator value to identify the web element.
|
178
|
+
by (selenium.webdriver.common.by.By, optional): The locator strategy to use.
|
179
|
+
Defaults to By.XPATH.
|
180
|
+
timeout (int, optional): The maximum time to wait for the element to appear, in seconds.
|
181
|
+
Defaults to 12.
|
182
|
+
display_message (bool, optional): Whether to display an error message if the element
|
183
|
+
is not found. Defaults to True.
|
184
|
+
Returns:
|
185
|
+
selenium.webdriver.remote.webelement.WebElement: The located web element if found.
|
186
|
+
None: If the element is not found or an exception occurs.
|
187
|
+
Raises:
|
188
|
+
Exception: Propagates any exception encountered during the element search if
|
189
|
+
`display_message` is set to False.
|
190
|
+
"""
|
87
191
|
|
88
192
|
try:
|
89
193
|
sleep(2)
|
@@ -103,6 +207,14 @@ class Browser():
|
|
103
207
|
|
104
208
|
# navigate
|
105
209
|
def get(self, url: str, display_message: bool = False):
|
210
|
+
"""
|
211
|
+
Navigates the browser to the specified URL.
|
212
|
+
Args:
|
213
|
+
url (str): The URL to navigate to.
|
214
|
+
display_message (bool, optional): If True, displays a success message upon navigation. Defaults to False.
|
215
|
+
Raises:
|
216
|
+
Exception: If an error occurs while navigating to the URL, it logs the error message.
|
217
|
+
"""
|
106
218
|
|
107
219
|
try:
|
108
220
|
self.driver.get(url)
|
@@ -112,7 +224,14 @@ class Browser():
|
|
112
224
|
error_print(f'Erro ao navegar para a URL: {url}. Error: {str(e)}.')
|
113
225
|
|
114
226
|
|
115
|
-
def
|
227
|
+
def _close_all_browsers(self):
|
228
|
+
"""
|
229
|
+
Forcefully closes all instances of Google Chrome running on the system.
|
230
|
+
This method uses the `taskkill` command to terminate all processes with the name
|
231
|
+
"chrome.exe". Any errors during the execution of the command are silently ignored.
|
232
|
+
Note:
|
233
|
+
This method is specific to Windows operating systems and will not work on other platforms.
|
234
|
+
"""
|
116
235
|
|
117
236
|
try:
|
118
237
|
os.system('taskkill /F /IM chrome.exe >nul 2>&1')
|
@@ -121,6 +240,24 @@ class Browser():
|
|
121
240
|
|
122
241
|
|
123
242
|
def close_browser(self, display_message: bool = False):
|
243
|
+
"""
|
244
|
+
Fecha o navegador controlado pelo Selenium e encerra os processos relacionados ao Chrome.
|
245
|
+
Este método tenta fechar o navegador de forma ordenada utilizando os métodos `close` e `quit` do Selenium.
|
246
|
+
Caso esses métodos falhem, ele força o encerramento do processo do Chrome associado à porta de depuração remota.
|
247
|
+
Em último caso, pode encerrar todos os processos do Chrome relacionados à porta especificada.
|
248
|
+
Args:
|
249
|
+
display_message (bool): Indica se mensagens de status devem ser exibidas durante o processo de fechamento.
|
250
|
+
Comportamento:
|
251
|
+
- Tenta fechar o navegador utilizando `self.driver.close()` e `self.driver.quit()`.
|
252
|
+
- Aguarda um momento para liberar o processo.
|
253
|
+
- Força o encerramento do processo do Chrome associado à porta de depuração remota.
|
254
|
+
- Verifica se o processo foi encerrado e tenta métodos mais agressivos, se necessário.
|
255
|
+
- Em caso de falha crítica, tenta encerrar todos os processos do Chrome relacionados à porta especificada.
|
256
|
+
Exceções:
|
257
|
+
- Captura e exibe mensagens de erro caso ocorra falha ao fechar o navegador.
|
258
|
+
Observação:
|
259
|
+
Use com cautela, especialmente o encerramento extremo, pois pode afetar outros processos do Chrome em execução.
|
260
|
+
"""
|
124
261
|
|
125
262
|
try:
|
126
263
|
# Primeiro tenta fechar todas as janelas via Selenium
|
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,9 +1,13 @@
|
|
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():
|
9
13
|
"""
|
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,19 @@
|
|
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
|
+
|
16
|
+
|
8
17
|
class File():
|
9
18
|
"""
|
10
19
|
Class that provides utilities for file management, including creation, deletion, and manipulation of files.
|
@@ -170,7 +179,7 @@ class File():
|
|
170
179
|
full_path_with_name = fr'{path_to_create}/{name_file}'
|
171
180
|
|
172
181
|
with open(full_path_with_name, 'w', encoding='utf-8') as file:
|
173
|
-
file.write('[
|
182
|
+
file.write('[RPA Suite] - Running Flag File')
|
174
183
|
if display_message: success_print("Flag file created.")
|
175
184
|
|
176
185
|
except Exception as e:
|
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,193 @@
|
|
1
|
+
# rpa_suite/core/parallel.py
|
2
|
+
|
3
|
+
from multiprocessing import Process, Manager
|
4
|
+
from typing import Any, Callable, Dict, Optional, TypeVar, Generic
|
5
|
+
import time
|
6
|
+
import traceback
|
7
|
+
|
8
|
+
# Definir tipo genérico para o retorno da função
|
9
|
+
T = TypeVar('T')
|
10
|
+
|
11
|
+
class ParallelRunner(Generic[T]):
|
12
|
+
|
13
|
+
"""
|
14
|
+
Classe para executar funções em paralelo mantendo o fluxo principal da aplicação.
|
15
|
+
|
16
|
+
Permite iniciar uma função em um processo separado e obter seu resultado posteriormente.
|
17
|
+
"""
|
18
|
+
|
19
|
+
def __init__(self):
|
20
|
+
"""Inicializa o ParallelRunner."""
|
21
|
+
self._manager = Manager()
|
22
|
+
self._result_dict = self._manager.dict()
|
23
|
+
self._process = None
|
24
|
+
self._start_time = None
|
25
|
+
|
26
|
+
@staticmethod
|
27
|
+
def _execute_function(function, args, kwargs, result_dict):
|
28
|
+
"""
|
29
|
+
Função estática que executa a função alvo e armazena o resultado.
|
30
|
+
Esta função precisa ser definida no nível do módulo para ser "picklable".
|
31
|
+
"""
|
32
|
+
try:
|
33
|
+
# Executa a função do usuário com os argumentos fornecidos
|
34
|
+
result = function(*args, **kwargs)
|
35
|
+
|
36
|
+
# Armazena o resultado no dicionário compartilhado
|
37
|
+
result_dict['status'] = 'success'
|
38
|
+
result_dict['result'] = result
|
39
|
+
|
40
|
+
# Para debug
|
41
|
+
print(f"[Processo Filho] Resultado calculado: {result}")
|
42
|
+
print(f"[Processo Filho] Dicionário de resultados: {dict(result_dict)}")
|
43
|
+
|
44
|
+
except Exception as e:
|
45
|
+
# Em caso de erro, armazena informações sobre o erro
|
46
|
+
result_dict['status'] = 'error'
|
47
|
+
result_dict['error'] = str(e)
|
48
|
+
result_dict['traceback'] = traceback.format_exc()
|
49
|
+
|
50
|
+
# Para debug
|
51
|
+
print(f"[Processo Filho] Erro ocorrido: {str(e)}")
|
52
|
+
|
53
|
+
def run(self, function: Callable[..., T], *args, **kwargs) -> 'ParallelRunner[T]':
|
54
|
+
"""
|
55
|
+
Inicia a execução da função em um processo paralelo.
|
56
|
+
|
57
|
+
Args:
|
58
|
+
function: Função a ser executada em paralelo
|
59
|
+
*args: Argumentos posicionais para a função
|
60
|
+
**kwargs: Argumentos nomeados para a função
|
61
|
+
|
62
|
+
Returns:
|
63
|
+
self: Retorna a própria instância para permitir chamadas encadeadas
|
64
|
+
"""
|
65
|
+
# Limpar resultado anterior, se houver
|
66
|
+
if self._result_dict:
|
67
|
+
self._result_dict.clear()
|
68
|
+
|
69
|
+
# Configura valores iniciais no dicionário compartilhado
|
70
|
+
self._result_dict['status'] = 'running'
|
71
|
+
|
72
|
+
# Inicia o processo com a função auxiliar estática
|
73
|
+
self._process = Process(
|
74
|
+
target=ParallelRunner._execute_function,
|
75
|
+
args=(function, args, kwargs, self._result_dict)
|
76
|
+
)
|
77
|
+
self._process.daemon = True # Processo filho termina quando o principal termina
|
78
|
+
self._process.start()
|
79
|
+
self._start_time = time.time()
|
80
|
+
|
81
|
+
return self
|
82
|
+
|
83
|
+
def is_running(self) -> bool:
|
84
|
+
"""
|
85
|
+
Verifica se o processo ainda está em execução.
|
86
|
+
|
87
|
+
Returns:
|
88
|
+
bool: True se o processo ainda estiver em execução, False caso contrário
|
89
|
+
"""
|
90
|
+
if self._process is None:
|
91
|
+
return False
|
92
|
+
return self._process.is_alive()
|
93
|
+
|
94
|
+
def get_result(self, timeout: Optional[float] = None, terminate_on_timeout: bool = True) -> Dict[str, Any]:
|
95
|
+
"""
|
96
|
+
Obtém o resultado da execução paralela.
|
97
|
+
|
98
|
+
Args:
|
99
|
+
timeout: Tempo máximo (em segundos) para aguardar o término do processo
|
100
|
+
None significa esperar indefinidamente
|
101
|
+
terminate_on_timeout: Se True, termina o processo caso o timeout seja atingido
|
102
|
+
|
103
|
+
Returns:
|
104
|
+
Dict contendo:
|
105
|
+
- success: bool indicando se a operação foi bem-sucedida
|
106
|
+
- result: resultado da função (se bem-sucedida)
|
107
|
+
- error: mensagem de erro (se houver)
|
108
|
+
- traceback: stack trace completo (se houver erro)
|
109
|
+
- execution_time: tempo de execução em segundos
|
110
|
+
- terminated: True se o processo foi terminado por timeout
|
111
|
+
"""
|
112
|
+
if self._process is None:
|
113
|
+
return {
|
114
|
+
'success': False,
|
115
|
+
'error': 'Nenhum processo foi iniciado',
|
116
|
+
'execution_time': 0,
|
117
|
+
'terminated': False
|
118
|
+
}
|
119
|
+
|
120
|
+
# Aguarda o processo terminar com tempo limite
|
121
|
+
self._process.join(timeout=timeout)
|
122
|
+
execution_time = time.time() - self._start_time
|
123
|
+
|
124
|
+
# Preparamos o dicionário de resposta
|
125
|
+
result = {
|
126
|
+
'execution_time': execution_time,
|
127
|
+
'terminated': False
|
128
|
+
}
|
129
|
+
|
130
|
+
# Debug - mostra o dicionário compartilhado
|
131
|
+
print(f"[Processo Principal] Dicionário compartilhado: {dict(self._result_dict)}")
|
132
|
+
|
133
|
+
# Verifica se o processo terminou ou se atingiu o timeout
|
134
|
+
if self._process.is_alive():
|
135
|
+
if terminate_on_timeout:
|
136
|
+
self._process.terminate()
|
137
|
+
self._process.join(timeout=1) # Pequeno timeout para garantir que o processo termine
|
138
|
+
result['terminated'] = True
|
139
|
+
result['success'] = False
|
140
|
+
result['error'] = f'Operação cancelada por timeout após {execution_time:.2f} segundos'
|
141
|
+
else:
|
142
|
+
result['success'] = False
|
143
|
+
result['error'] = f'Operação ainda em execução após {execution_time:.2f} segundos'
|
144
|
+
else:
|
145
|
+
# Processo terminou normalmente - verificamos o status
|
146
|
+
status = self._result_dict.get('status', 'unknown')
|
147
|
+
|
148
|
+
if status == 'success':
|
149
|
+
result['success'] = True
|
150
|
+
# Garantimos que o resultado está sendo copiado corretamente
|
151
|
+
if 'result' in self._result_dict:
|
152
|
+
result['result'] = self._result_dict['result']
|
153
|
+
else:
|
154
|
+
result['success'] = False
|
155
|
+
result['error'] = 'Resultado não encontrado no dicionário compartilhado'
|
156
|
+
else:
|
157
|
+
result['success'] = False
|
158
|
+
result['error'] = self._result_dict.get('error', 'Erro desconhecido')
|
159
|
+
if 'traceback' in self._result_dict:
|
160
|
+
result['traceback'] = self._result_dict['traceback']
|
161
|
+
|
162
|
+
# Finaliza o Manager se o processo terminou e não estamos mais esperando resultado
|
163
|
+
if not self._process.is_alive() and (result.get('success', False) or result.get('terminated', False)):
|
164
|
+
self._cleanup()
|
165
|
+
|
166
|
+
return result
|
167
|
+
|
168
|
+
def terminate(self) -> None:
|
169
|
+
"""
|
170
|
+
Termina o processo em execução.
|
171
|
+
"""
|
172
|
+
if self._process and self._process.is_alive():
|
173
|
+
self._process.terminate()
|
174
|
+
self._process.join(timeout=1)
|
175
|
+
self._cleanup()
|
176
|
+
|
177
|
+
def _cleanup(self) -> None:
|
178
|
+
"""
|
179
|
+
Limpa os recursos utilizados pelo processo.
|
180
|
+
"""
|
181
|
+
if hasattr(self, '_manager') and self._manager is not None:
|
182
|
+
try:
|
183
|
+
self._manager.shutdown()
|
184
|
+
except Exception:
|
185
|
+
pass
|
186
|
+
self._manager = None
|
187
|
+
self._process = None
|
188
|
+
|
189
|
+
def __del__(self):
|
190
|
+
"""
|
191
|
+
Destrutor da classe, garante que recursos sejam liberados.
|
192
|
+
"""
|
193
|
+
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]]:
|