rpa-suite 1.6.2__py3-none-any.whl → 1.6.3__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 +1 -1
- rpa_suite/core/__init__.py +5 -1
- rpa_suite/core/artemis.py +445 -0
- rpa_suite/core/asyncrun.py +15 -8
- rpa_suite/core/browser.py +44 -41
- rpa_suite/core/clock.py +46 -13
- rpa_suite/core/date.py +41 -16
- rpa_suite/core/dir.py +29 -72
- rpa_suite/core/email.py +26 -15
- rpa_suite/core/file.py +46 -43
- rpa_suite/core/iris.py +87 -79
- rpa_suite/core/log.py +134 -46
- rpa_suite/core/parallel.py +185 -182
- rpa_suite/core/print.py +119 -96
- rpa_suite/core/regex.py +26 -26
- rpa_suite/core/validate.py +20 -76
- rpa_suite/functions/__init__.py +1 -1
- rpa_suite/suite.py +13 -1
- rpa_suite/utils/__init__.py +1 -1
- rpa_suite/utils/system.py +64 -61
- {rpa_suite-1.6.2.dist-info → rpa_suite-1.6.3.dist-info}/METADATA +4 -16
- rpa_suite-1.6.3.dist-info/RECORD +27 -0
- rpa_suite-1.6.2.dist-info/RECORD +0 -26
- {rpa_suite-1.6.2.dist-info → rpa_suite-1.6.3.dist-info}/WHEEL +0 -0
- {rpa_suite-1.6.2.dist-info → rpa_suite-1.6.3.dist-info}/licenses/LICENSE +0 -0
- {rpa_suite-1.6.2.dist-info → rpa_suite-1.6.3.dist-info}/top_level.txt +0 -0
rpa_suite/core/browser.py
CHANGED
@@ -14,8 +14,12 @@ from selenium.webdriver.support import expected_conditions as EC
|
|
14
14
|
from webdriver_manager.chrome import ChromeDriverManager
|
15
15
|
|
16
16
|
# imports internal
|
17
|
-
from rpa_suite.functions._printer import
|
17
|
+
from rpa_suite.functions._printer import alert_print, success_print
|
18
18
|
|
19
|
+
class BrowserError(Exception):
|
20
|
+
"""Custom exception for Browser errors."""
|
21
|
+
def __init__(self, message):
|
22
|
+
super().__init__(f'BrowserError: {message}')
|
19
23
|
|
20
24
|
class Browser:
|
21
25
|
"""
|
@@ -36,16 +40,16 @@ class Browser:
|
|
36
40
|
optionally closes all Chrome instances running on the same port.
|
37
41
|
configure_browser() -> None:
|
38
42
|
Configures the browser with debugging options and initializes the WebDriver.
|
39
|
-
start_browser(close_chrome_on_this_port: bool = True,
|
43
|
+
start_browser(close_chrome_on_this_port: bool = True, verbose: bool = False):
|
40
44
|
Starts the Chrome browser with the specified debugging port and initializes
|
41
45
|
the WebDriver.
|
42
|
-
find_ele(value, by=By.XPATH, timeout=12,
|
46
|
+
find_ele(value, by=By.XPATH, timeout=12, verbose=True):
|
43
47
|
Finds a single element on the page using the specified locator strategy.
|
44
|
-
get(url: str,
|
48
|
+
get(url: str, verbose: bool = False):
|
45
49
|
Navigates the browser to the specified URL.
|
46
50
|
_close_all_browsers():
|
47
51
|
Closes all Chrome processes forcefully.
|
48
|
-
close_browser(
|
52
|
+
close_browser(verbose: bool = False):
|
49
53
|
Closes the browser instance and terminates the associated Chrome processes.
|
50
54
|
|
51
55
|
pt-br
|
@@ -68,16 +72,16 @@ class Browser:
|
|
68
72
|
na mesma porta.
|
69
73
|
configure_browser() -> None:
|
70
74
|
Configura o navegador com opções de depuração e inicializa o WebDriver.
|
71
|
-
start_browser(close_chrome_on_this_port: bool = True,
|
75
|
+
start_browser(close_chrome_on_this_port: bool = True, verbose: bool = False):
|
72
76
|
Inicia o navegador Chrome com a porta de depuração especificada e inicializa
|
73
77
|
o WebDriver.
|
74
|
-
find_ele(value, by=By.XPATH, timeout=12,
|
78
|
+
find_ele(value, by=By.XPATH, timeout=12, verbose=True):
|
75
79
|
Localiza um único elemento na página usando a estratégia de localização especificada.
|
76
|
-
get(url: str,
|
80
|
+
get(url: str, verbose: bool = False):
|
77
81
|
Navega o navegador para a URL especificada.
|
78
82
|
_close_all_browsers():
|
79
83
|
Fecha todos os processos do Chrome de forma forçada.
|
80
|
-
close_browser(
|
84
|
+
close_browser(verbose: bool = False):
|
81
85
|
Fecha a instância do navegador e termina os processos associados do Chrome.
|
82
86
|
"""
|
83
87
|
|
@@ -85,13 +89,12 @@ class Browser:
|
|
85
89
|
port: int = None
|
86
90
|
path_driver = None
|
87
91
|
|
88
|
-
def __init__(self, port: int = 9393, close_browser_on_this_port: bool = False):
|
92
|
+
def __init__(self, port: int = 9393, close_browser_on_this_port: bool = False) -> None:
|
89
93
|
self.port = port
|
90
94
|
self.path_driver = ChromeDriverManager().install()
|
91
95
|
|
92
96
|
if close_browser_on_this_port:
|
93
97
|
self._close_all_browsers()
|
94
|
-
...
|
95
98
|
|
96
99
|
def configure_browser(self) -> None:
|
97
100
|
"""
|
@@ -116,7 +119,7 @@ class Browser:
|
|
116
119
|
|
117
120
|
# Verifica se o caminho do driver está correto
|
118
121
|
if not os.path.exists(self.path_driver):
|
119
|
-
raise FileNotFoundError(f"
|
122
|
+
raise FileNotFoundError(f"Driver path not found: {self.path_driver}")
|
120
123
|
|
121
124
|
# Create driver with options and chromedriver path
|
122
125
|
self.driver = webdriver.Chrome(
|
@@ -126,14 +129,14 @@ class Browser:
|
|
126
129
|
)
|
127
130
|
|
128
131
|
except Exception as e:
|
129
|
-
|
132
|
+
BrowserError(f"Error configure_brower: {str(e)}.")
|
130
133
|
|
131
|
-
def start_browser(self, close_chrome_on_this_port: bool = True,
|
134
|
+
def start_browser(self, close_chrome_on_this_port: bool = True, verbose: bool = False):
|
132
135
|
"""
|
133
136
|
Starts a Chrome browser instance with remote debugging enabled.
|
134
137
|
Args:
|
135
138
|
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.
|
136
|
-
|
139
|
+
verbose (bool): If True, displays a success message upon successfully starting the browser. Defaults to False.
|
137
140
|
Raises:
|
138
141
|
Exception: If an error occurs while starting the browser or connecting to the debugging port.
|
139
142
|
Behavior:
|
@@ -141,7 +144,7 @@ class Browser:
|
|
141
144
|
- Launches Chrome with the specified debugging port and user data directory.
|
142
145
|
- Waits until Chrome is fully initialized and accessible via the debugging port.
|
143
146
|
- Configures the browser instance using the `configure_browser` method.
|
144
|
-
- Optionally displays a success message if `
|
147
|
+
- Optionally displays a success message if `verbose` is True.
|
145
148
|
"""
|
146
149
|
|
147
150
|
try:
|
@@ -166,13 +169,13 @@ class Browser:
|
|
166
169
|
# Inicializa o Chrome com as opções
|
167
170
|
self.configure_browser()
|
168
171
|
|
169
|
-
if
|
170
|
-
success_print(f"Browser:
|
172
|
+
if verbose:
|
173
|
+
success_print(f"Browser: Started successfully!")
|
171
174
|
|
172
175
|
except Exception as e:
|
173
|
-
|
176
|
+
BrowserError(f"Error starting browser: {str(e)}.")
|
174
177
|
|
175
|
-
def find_ele(self, value: str, by: By = By.XPATH, timeout=12,
|
178
|
+
def find_ele(self, value: str, by: By = By.XPATH, timeout=12, verbose=True):
|
176
179
|
"""
|
177
180
|
Locate and return a web element on the page using the specified locator strategy.
|
178
181
|
Args:
|
@@ -181,14 +184,14 @@ class Browser:
|
|
181
184
|
Defaults to By.XPATH.
|
182
185
|
timeout (int, optional): The maximum time to wait for the element to appear, in seconds.
|
183
186
|
Defaults to 12.
|
184
|
-
|
187
|
+
verbose (bool, optional): Whether to display an error message if the element
|
185
188
|
is not found. Defaults to True.
|
186
189
|
Returns:
|
187
190
|
selenium.webdriver.remote.webelement.WebElement: The located web element if found.
|
188
191
|
None: If the element is not found or an exception occurs.
|
189
192
|
Raises:
|
190
193
|
Exception: Propagates any exception encountered during the element search if
|
191
|
-
`
|
194
|
+
`verbose` is set to False.
|
192
195
|
"""
|
193
196
|
|
194
197
|
try:
|
@@ -198,8 +201,8 @@ class Browser:
|
|
198
201
|
|
199
202
|
except Exception as e:
|
200
203
|
|
201
|
-
if
|
202
|
-
|
204
|
+
if verbose:
|
205
|
+
BrowserError(f"Error find_ele (FindElement): {str(e)}.")
|
203
206
|
return None
|
204
207
|
else:
|
205
208
|
return None
|
@@ -208,23 +211,23 @@ class Browser:
|
|
208
211
|
...
|
209
212
|
|
210
213
|
# navigate
|
211
|
-
def get(self, url: str,
|
214
|
+
def get(self, url: str, verbose: bool = False):
|
212
215
|
"""
|
213
216
|
Navigates the browser to the specified URL.
|
214
217
|
Args:
|
215
218
|
url (str): The URL to navigate to.
|
216
|
-
|
219
|
+
verbose (bool, optional): If True, displays a success message upon navigation. Defaults to False.
|
217
220
|
Raises:
|
218
221
|
Exception: If an error occurs while navigating to the URL, it logs the error message.
|
219
222
|
"""
|
220
223
|
|
221
224
|
try:
|
222
225
|
self.driver.get(url)
|
223
|
-
if
|
224
|
-
success_print(f"Browser:
|
226
|
+
if verbose:
|
227
|
+
success_print(f"Browser: Navigating to: {url}")
|
225
228
|
|
226
229
|
except Exception as e:
|
227
|
-
|
230
|
+
BrowserError(f"Error navigating to URL: {url}. Error: {str(e)}.")
|
228
231
|
|
229
232
|
def _close_all_browsers(self):
|
230
233
|
"""
|
@@ -240,14 +243,14 @@ class Browser:
|
|
240
243
|
except:
|
241
244
|
pass
|
242
245
|
|
243
|
-
def close_browser(self,
|
246
|
+
def close_browser(self, verbose: bool = False):
|
244
247
|
"""
|
245
248
|
Fecha o navegador controlado pelo Selenium e encerra os processos relacionados ao Chrome.
|
246
249
|
Este método tenta fechar o navegador de forma ordenada utilizando os métodos `close` e `quit` do Selenium.
|
247
250
|
Caso esses métodos falhem, ele força o encerramento do processo do Chrome associado à porta de depuração remota.
|
248
251
|
Em último caso, pode encerrar todos os processos do Chrome relacionados à porta especificada.
|
249
252
|
Args:
|
250
|
-
|
253
|
+
verbose (bool): Indica se mensagens de status devem ser exibidas durante o processo de fechamento.
|
251
254
|
Comportamento:
|
252
255
|
- Tenta fechar o navegador utilizando `self.driver.close()` e `self.driver.quit()`.
|
253
256
|
- Aguarda um momento para liberar o processo.
|
@@ -291,26 +294,26 @@ class Browser:
|
|
291
294
|
os.system(
|
292
295
|
f'taskkill /f /im chrome.exe /fi "commandline like *--remote-debugging-port={str(self.port)}*" /t >nul 2>&1'
|
293
296
|
)
|
294
|
-
if
|
295
|
-
alert_print("Browser:
|
297
|
+
if verbose:
|
298
|
+
alert_print("Browser: Closed forcefully!")
|
296
299
|
|
297
300
|
else:
|
298
|
-
if
|
299
|
-
success_print("Browser:
|
301
|
+
if verbose:
|
302
|
+
success_print("Browser: Closed successfully!")
|
300
303
|
|
301
304
|
except Exception as e:
|
302
305
|
|
303
306
|
try:
|
304
|
-
if
|
305
|
-
alert_print(f"
|
307
|
+
if verbose:
|
308
|
+
alert_print(f"Error closing browser: {str(e)}, Trying stronger method!")
|
306
309
|
|
307
310
|
# Último recurso - mata todos os processos do Chrome (use com cautela)
|
308
311
|
os.system(
|
309
312
|
f'taskkill /f /im chrome.exe /fi "commandline like *--remote-debugging-port={str(self.port)}*" /t >nul 2>&1'
|
310
313
|
)
|
311
|
-
if
|
312
|
-
alert_print("Browser:
|
314
|
+
if verbose:
|
315
|
+
alert_print("Browser: Closed with extreme force!")
|
313
316
|
|
314
317
|
except Exception as error_ultimate:
|
315
|
-
if
|
316
|
-
|
318
|
+
if verbose:
|
319
|
+
BrowserError(f"Critical failure trying to close browser! Error: {str(error_ultimate)}!")
|
rpa_suite/core/clock.py
CHANGED
@@ -6,8 +6,12 @@ from typing import Callable, Any
|
|
6
6
|
from datetime import datetime as dt
|
7
7
|
|
8
8
|
# imports internal
|
9
|
-
from rpa_suite.functions._printer import
|
9
|
+
from rpa_suite.functions._printer import success_print
|
10
10
|
|
11
|
+
class ClockError(Exception):
|
12
|
+
"""Custom exception for Clock errors."""
|
13
|
+
def __init__(self, message):
|
14
|
+
super().__init__(f'ClockError: {message}')
|
11
15
|
|
12
16
|
class Clock:
|
13
17
|
"""
|
@@ -42,7 +46,39 @@ class Clock:
|
|
42
46
|
>>> rpa.clock.exec_at_hour("14:30", minha_funcao)
|
43
47
|
"""
|
44
48
|
|
45
|
-
def __init__(self):
|
49
|
+
def __init__(self) -> None:
|
50
|
+
"""
|
51
|
+
Class that provides utilities for time manipulation and stopwatch.
|
52
|
+
|
53
|
+
This class offers functionalities for:
|
54
|
+
- Timed function execution
|
55
|
+
- Execution time control
|
56
|
+
- Task scheduling
|
57
|
+
|
58
|
+
Methods:
|
59
|
+
exec_at_hour: Executes a function at a specific time
|
60
|
+
|
61
|
+
The Clock class is part of RPA Suite and can be accessed through the rpa object:
|
62
|
+
>>> from rpa_suite import rpa
|
63
|
+
>>> rpa.clock.exec_at_hour("14:30", my_function)
|
64
|
+
|
65
|
+
pt-br
|
66
|
+
----------
|
67
|
+
Classe que fornece utilitários para manipulação de tempo e cronômetro.
|
68
|
+
|
69
|
+
Esta classe oferece funcionalidades para:
|
70
|
+
- Execução temporizada de funções
|
71
|
+
- Controle de tempo de execução
|
72
|
+
- Agendamento de tarefas
|
73
|
+
|
74
|
+
Métodos:
|
75
|
+
exec_at_hour: Executa uma função em um horário específico
|
76
|
+
|
77
|
+
A classe Clock é parte do RPA Suite e pode ser acessada através do objeto rpa:
|
78
|
+
>>> from rpa_suite import rpa
|
79
|
+
>>> rpa.clock.exec_at_hour("14:30", minha_funcao)
|
80
|
+
"""
|
81
|
+
pass
|
46
82
|
|
47
83
|
def exec_at_hour(
|
48
84
|
self,
|
@@ -127,7 +163,7 @@ class Clock:
|
|
127
163
|
run = False
|
128
164
|
result["tried"] = not run
|
129
165
|
result["success"] = False
|
130
|
-
|
166
|
+
ClockError(
|
131
167
|
f"An error occurred that prevented the function from executing: {fn_to_exec.__name__} correctly. Error: {str(e)}"
|
132
168
|
)
|
133
169
|
break
|
@@ -147,10 +183,9 @@ class Clock:
|
|
147
183
|
run = False
|
148
184
|
result["tried"] = not run
|
149
185
|
result["success"] = False
|
150
|
-
|
186
|
+
ClockError(
|
151
187
|
f"An error occurred that prevented the function from executing: {fn_to_exec.__name__} correctly. Error: {str(e)}"
|
152
|
-
)
|
153
|
-
break
|
188
|
+
) from e
|
154
189
|
else:
|
155
190
|
time.sleep(30)
|
156
191
|
now = dt.now()
|
@@ -161,10 +196,8 @@ class Clock:
|
|
161
196
|
return result
|
162
197
|
|
163
198
|
except Exception as e:
|
164
|
-
|
165
199
|
result["success"] = False
|
166
|
-
|
167
|
-
return result
|
200
|
+
raise ClockError(str(e)) from e
|
168
201
|
|
169
202
|
def wait_for_exec(self, wait_time: int, fn_to_exec: Callable[..., Any], *args, **kwargs) -> dict[str, bool]:
|
170
203
|
"""
|
@@ -222,9 +255,9 @@ class Clock:
|
|
222
255
|
|
223
256
|
except Exception as e:
|
224
257
|
result["success"] = False
|
225
|
-
|
258
|
+
ClockError(
|
226
259
|
f"Error while trying to wait to execute the function: {fn_to_exec.__name__} \nMessage: {str(e)}"
|
227
|
-
)
|
260
|
+
) from e
|
228
261
|
|
229
262
|
return result
|
230
263
|
|
@@ -284,8 +317,8 @@ class Clock:
|
|
284
317
|
|
285
318
|
except Exception as e:
|
286
319
|
result["success"] = False
|
287
|
-
|
320
|
+
ClockError(
|
288
321
|
f"Error while trying to wait to execute the function: {fn_to_exec.__name__} \nMessage: {str(e)}"
|
289
|
-
)
|
322
|
+
) from e
|
290
323
|
|
291
324
|
return result
|
rpa_suite/core/date.py
CHANGED
@@ -5,9 +5,10 @@ import datetime as dt
|
|
5
5
|
from typing import Optional as Op
|
6
6
|
from typing import Tuple
|
7
7
|
|
8
|
-
|
9
|
-
|
10
|
-
|
8
|
+
class DateError(Exception):
|
9
|
+
"""Custom exception for Date errors."""
|
10
|
+
def __init__(self, message):
|
11
|
+
super().__init__(f'DateError: {message}')
|
11
12
|
|
12
13
|
class Date:
|
13
14
|
"""
|
@@ -42,7 +43,39 @@ class Date:
|
|
42
43
|
>>> hora, minuto, segundo = rpa.date.get_hms()
|
43
44
|
"""
|
44
45
|
|
45
|
-
def __init__(self):
|
46
|
+
def __init__(self) -> None:
|
47
|
+
"""
|
48
|
+
Class that provides utilities for date manipulation and formatting.
|
49
|
+
|
50
|
+
This class offers functionalities for:
|
51
|
+
- Getting current time components (hours, minutes, seconds)
|
52
|
+
- Date formatting and manipulation
|
53
|
+
- Date validation and conversion
|
54
|
+
|
55
|
+
Methods:
|
56
|
+
get_hms: Returns current time as tuple of hour, minute, second
|
57
|
+
|
58
|
+
The Date class is part of RPA Suite and can be accessed through the rpa object:
|
59
|
+
>>> from rpa_suite import rpa
|
60
|
+
>>> hour, minute, second = rpa.date.get_hms()
|
61
|
+
|
62
|
+
pt-br
|
63
|
+
----------
|
64
|
+
Classe que fornece utilitários para manipulação e formatação de datas.
|
65
|
+
|
66
|
+
Esta classe oferece funcionalidades para:
|
67
|
+
- Obtenção de componentes do tempo atual (horas, minutos, segundos)
|
68
|
+
- Formatação e manipulação de datas
|
69
|
+
- Validação e conversão de datas
|
70
|
+
|
71
|
+
Métodos:
|
72
|
+
get_hms: Retorna o horário atual como tupla de hora, minuto, segundo
|
73
|
+
|
74
|
+
A classe Date é parte do RPA Suite e pode ser acessada através do objeto rpa:
|
75
|
+
>>> from rpa_suite import rpa
|
76
|
+
>>> hora, minuto, segundo = rpa.date.get_hms()
|
77
|
+
"""
|
78
|
+
pass
|
46
79
|
|
47
80
|
def get_hms(self) -> Tuple[Op[str], Op[str], Op[str]]:
|
48
81
|
"""
|
@@ -106,13 +139,9 @@ class Date:
|
|
106
139
|
return hours, minutes, seconds
|
107
140
|
|
108
141
|
except Exception as e:
|
109
|
-
|
110
|
-
error_print(f"Unable to capture the time. Error: {str(e)}")
|
111
|
-
return None, None, None
|
112
|
-
|
142
|
+
raise e from e
|
113
143
|
except Exception as e:
|
114
|
-
|
115
|
-
return None, None, None
|
144
|
+
DateError(f"Error function: {self.get_hms.__name__}! {str(e)}.") from e
|
116
145
|
|
117
146
|
def get_dmy(self) -> Tuple[Op[str], Op[str], Op[str]]:
|
118
147
|
"""
|
@@ -160,10 +189,6 @@ class Date:
|
|
160
189
|
return day_got, month_got, year_got
|
161
190
|
|
162
191
|
except Exception as e:
|
163
|
-
|
164
|
-
error_print(f"Unable to capture the time. Error: {str(e)}")
|
165
|
-
return None, None, None
|
166
|
-
|
192
|
+
raise e from e
|
167
193
|
except Exception as e:
|
168
|
-
|
169
|
-
return None, None, None
|
194
|
+
DateError(f"Erro function: {self.get_dmy.__name__}! {str(e)}.")
|
rpa_suite/core/dir.py
CHANGED
@@ -6,8 +6,13 @@ import shutil
|
|
6
6
|
from typing import Union
|
7
7
|
|
8
8
|
# imports internal
|
9
|
-
from rpa_suite.functions._printer import
|
9
|
+
from rpa_suite.functions._printer import alert_print, success_print
|
10
10
|
|
11
|
+
class DirectoryError(Exception):
|
12
|
+
"""Custom exception for Directory errors."""
|
13
|
+
def __init__(self, message):
|
14
|
+
clean_message = message.replace("DirectoryError:", "").strip()
|
15
|
+
super().__init__(f'DirectoryError: {clean_message}')
|
11
16
|
|
12
17
|
class Directory:
|
13
18
|
"""
|
@@ -29,35 +34,17 @@ class Directory:
|
|
29
34
|
Parameters:
|
30
35
|
path_to_create (str): The full path where the temporary directory should be created. Default is 'default', which creates it in the current directory.
|
31
36
|
name_temp_dir (str): The name of the temporary directory to be created. Default is 'temp'.
|
32
|
-
|
33
|
-
pt-br
|
34
|
-
----------
|
35
|
-
Classe que fornece utilitários para gerenciamento de diretórios, incluindo criação, exclusão e manipulação de diretórios.
|
36
|
-
|
37
|
-
Esta classe oferece funcionalidades para:
|
38
|
-
- Criar diretórios temporários
|
39
|
-
- Excluir diretórios
|
40
|
-
- Verificar se um diretório existe
|
41
|
-
- Listar arquivos em um diretório
|
42
|
-
|
43
|
-
Métodos:
|
44
|
-
create_temp_dir: Cria um diretório temporário para operações com arquivos.
|
45
|
-
|
46
|
-
A classe Directory é parte do RPA Suite e pode ser acessada através do objeto rpa:
|
47
|
-
>>> from rpa_suite import rpa
|
48
|
-
>>> rpa.directory.create_temp_dir(path_to_create='minha_pasta', name_temp_dir='temp_dir')
|
49
|
-
|
50
|
-
Parâmetros:
|
51
|
-
path_to_create (str): O caminho completo onde o diretório temporário deve ser criado. O padrão é 'default', que o cria no diretório atual.
|
52
|
-
name_temp_dir (str): O nome do diretório temporário a ser criado. O padrão é 'temp'.
|
53
37
|
"""
|
54
38
|
|
55
39
|
def __init__(self):
|
56
40
|
"""
|
57
|
-
|
58
|
-
|
41
|
+
Constructor function of the Class that provides utilities for directory management,
|
42
|
+
including creation, deletion and manipulation of directories.
|
59
43
|
"""
|
60
|
-
|
44
|
+
try:
|
45
|
+
pass
|
46
|
+
except Exception as e:
|
47
|
+
raise DirectoryError(f"Error trying execute: {self.__init__.__name__}! {str(e)}.")
|
61
48
|
|
62
49
|
def create_temp_dir(
|
63
50
|
self,
|
@@ -66,7 +53,7 @@ class Directory:
|
|
66
53
|
display_message: bool = False,
|
67
54
|
) -> dict[str, Union[bool, str, None]]:
|
68
55
|
"""
|
69
|
-
Function responsible for creating a temporary directory to work with files and etc.
|
56
|
+
Function responsible for creating a temporary directory to work with files and etc.
|
70
57
|
|
71
58
|
Parameters:
|
72
59
|
----------
|
@@ -81,24 +68,6 @@ class Directory:
|
|
81
68
|
>>> type:dict
|
82
69
|
* 'success': bool - represents case the action was performed successfully
|
83
70
|
* 'path_created': str - path of the directory that was created on the process
|
84
|
-
|
85
|
-
Description: pt-br
|
86
|
-
----------
|
87
|
-
Função responsavel por criar diretório temporário para trabalhar com arquivos e etc. \n
|
88
|
-
|
89
|
-
Parametros:
|
90
|
-
----------
|
91
|
-
``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.
|
92
|
-
|
93
|
-
``name_temp_dir: str`` - deve ser uma string representando o nome do diretório temporário a ser criado. Se estiver vazio, o valor ``temp`` será usado como o nome padrão do diretório.
|
94
|
-
|
95
|
-
``display_message: bool`` - deve ser um bool para exibir mensagens no terminal, por padrão False.
|
96
|
-
|
97
|
-
Retorno:
|
98
|
-
----------
|
99
|
-
>>> type:dict
|
100
|
-
* 'success': bool - representa se ação foi realizada com sucesso
|
101
|
-
* 'path_created': str - path do diretório que foi criado no processo
|
102
71
|
"""
|
103
72
|
|
104
73
|
# Local Variables
|
@@ -117,7 +86,6 @@ class Directory:
|
|
117
86
|
|
118
87
|
# Create dir in this block
|
119
88
|
try:
|
120
|
-
|
121
89
|
# Successefully created
|
122
90
|
os.makedirs(full_path, exist_ok=False)
|
123
91
|
|
@@ -131,17 +99,18 @@ class Directory:
|
|
131
99
|
result["success"] = False
|
132
100
|
result["path_created"] = None
|
133
101
|
if display_message:
|
134
|
-
|
102
|
+
DirectoryError(f"Directory:'{full_path}' already exists.")
|
135
103
|
|
136
104
|
except PermissionError:
|
137
105
|
result["success"] = False
|
138
106
|
result["path_created"] = None
|
139
|
-
|
107
|
+
if display_message:
|
108
|
+
DirectoryError(f"Permission denied: Not possible to create Directory '{full_path}'.")
|
140
109
|
|
141
110
|
except Exception as e:
|
142
111
|
result["success"] = False
|
143
112
|
result["path_created"] = None
|
144
|
-
|
113
|
+
raise DirectoryError(f"Error trying execute: {self.create_temp_dir.__name__}! {str(e)}.")
|
145
114
|
|
146
115
|
return result
|
147
116
|
|
@@ -153,7 +122,7 @@ class Directory:
|
|
153
122
|
display_message: bool = False,
|
154
123
|
) -> dict[str, Union[bool, str, None]]:
|
155
124
|
"""
|
156
|
-
Function responsible for deleting a temporary directory.
|
125
|
+
Function responsible for deleting a temporary directory.
|
157
126
|
|
158
127
|
Parameters:
|
159
128
|
----------
|
@@ -168,24 +137,6 @@ class Directory:
|
|
168
137
|
>>> type:dict
|
169
138
|
* 'success': bool - represents case the action was performed successfully
|
170
139
|
* 'path_deleted': str - path of the directory that was deleted on the process
|
171
|
-
|
172
|
-
Description: pt-br
|
173
|
-
----------
|
174
|
-
Função responsavel por deletar diretório temporário. \n
|
175
|
-
|
176
|
-
Parametros:
|
177
|
-
----------
|
178
|
-
``path_to_delete: str`` - deve ser uma string com o path completo apontando para a pasta onde deve ser deletada a pasta temporaria, se estiver vazio sera usado valor ``default`` que deletará pasta no diretório atual onde o arquivo contendo esta função foi chamada.
|
179
|
-
|
180
|
-
``name_temp_dir: str`` - deve ser uma string representando o nome do diretório temporário a ser deletado. Se estiver vazio, o valor ``temp`` será usado como o nome padrão do diretório.
|
181
|
-
|
182
|
-
``delete_files: bool`` - deve ser um booleano indicando se deve deletar arquivos no diretório. Se for False, arquivos no diretório não serão deletados.
|
183
|
-
|
184
|
-
Retorno:
|
185
|
-
----------
|
186
|
-
>>> type:dict
|
187
|
-
* 'success': bool - representa se ação foi realizada com sucesso
|
188
|
-
* 'path_deleted': str - path do diretório que foi deletado no processo
|
189
140
|
"""
|
190
141
|
|
191
142
|
# Local Variables
|
@@ -204,7 +155,6 @@ class Directory:
|
|
204
155
|
|
205
156
|
# Delete dir in this block
|
206
157
|
try:
|
207
|
-
|
208
158
|
# Check if directory exists
|
209
159
|
if os.path.exists(full_path):
|
210
160
|
|
@@ -221,21 +171,28 @@ class Directory:
|
|
221
171
|
result["path_deleted"] = rf"{full_path}"
|
222
172
|
|
223
173
|
if display_message:
|
224
|
-
success_print(f"Directory:'{full_path}' successfully
|
174
|
+
success_print(f"Directory:'{full_path}' successfully deleted.")
|
225
175
|
else:
|
226
176
|
result["success"] = False
|
227
177
|
result["path_deleted"] = None
|
228
178
|
if display_message:
|
229
|
-
alert_print(f"Directory:'{full_path}'
|
179
|
+
alert_print(f"Directory:'{full_path}' doesn't exist.")
|
230
180
|
|
231
181
|
except PermissionError:
|
232
182
|
result["success"] = False
|
233
183
|
result["path_deleted"] = None
|
234
|
-
|
184
|
+
if display_message:
|
185
|
+
DirectoryError(f"Permission denied: Not possible to delete Directory '{full_path}'.")
|
186
|
+
|
187
|
+
except OSError as e:
|
188
|
+
result["success"] = False
|
189
|
+
result["path_deleted"] = None
|
190
|
+
if display_message:
|
191
|
+
DirectoryError(f"OS error occurred while deleting directory '{full_path}': {str(e)}")
|
235
192
|
|
236
193
|
except Exception as e:
|
237
194
|
result["success"] = False
|
238
195
|
result["path_deleted"] = None
|
239
|
-
|
196
|
+
raise DirectoryError(f"Error trying execute: {self.delete_temp_dir.__name__}! {str(e)}.")
|
240
197
|
|
241
198
|
return result
|