rpa-suite 0.9.3__tar.gz → 1.0.0__tar.gz

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.
Files changed (35) hide show
  1. {rpa_suite-0.9.3 → rpa_suite-1.0.0}/PKG-INFO +5 -3
  2. {rpa_suite-0.9.3 → rpa_suite-1.0.0}/README.md +3 -2
  3. {rpa_suite-0.9.3 → rpa_suite-1.0.0}/rpa_suite/clock/exec_at.py +43 -36
  4. {rpa_suite-0.9.3 → rpa_suite-1.0.0}/rpa_suite/clock/waiter.py +2 -2
  5. {rpa_suite-0.9.3 → rpa_suite-1.0.0}/rpa_suite/date/date.py +12 -5
  6. {rpa_suite-0.9.3 → rpa_suite-1.0.0}/rpa_suite/email/sender_smtp.py +2 -1
  7. {rpa_suite-0.9.3 → rpa_suite-1.0.0}/rpa_suite/file/counter.py +17 -16
  8. rpa_suite-1.0.0/rpa_suite/log/__create_log_dir.py +81 -0
  9. rpa_suite-1.0.0/rpa_suite/log/_variables.py +8 -0
  10. rpa_suite-1.0.0/rpa_suite/log/functions_logger.py +94 -0
  11. rpa_suite-0.9.3/rpa_suite/log/loggin.py → rpa_suite-1.0.0/rpa_suite/log/log_decorator.py +6 -6
  12. rpa_suite-1.0.0/rpa_suite/log/logger.py +111 -0
  13. {rpa_suite-0.9.3 → rpa_suite-1.0.0}/rpa_suite/log/printer.py +31 -24
  14. {rpa_suite-0.9.3 → rpa_suite-1.0.0}/rpa_suite/regex/list_from_text.py +7 -5
  15. {rpa_suite-0.9.3 → rpa_suite-1.0.0}/rpa_suite/suite.py +40 -15
  16. {rpa_suite-0.9.3 → rpa_suite-1.0.0}/rpa_suite.egg-info/PKG-INFO +5 -3
  17. {rpa_suite-0.9.3 → rpa_suite-1.0.0}/rpa_suite.egg-info/SOURCES.txt +5 -1
  18. {rpa_suite-0.9.3 → rpa_suite-1.0.0}/rpa_suite.egg-info/requires.txt +1 -0
  19. {rpa_suite-0.9.3 → rpa_suite-1.0.0}/setup.py +2 -2
  20. {rpa_suite-0.9.3 → rpa_suite-1.0.0}/LICENSE +0 -0
  21. {rpa_suite-0.9.3 → rpa_suite-1.0.0}/rpa_suite/__init__.py +0 -0
  22. {rpa_suite-0.9.3 → rpa_suite-1.0.0}/rpa_suite/clock/__init__.py +0 -0
  23. {rpa_suite-0.9.3 → rpa_suite-1.0.0}/rpa_suite/clock/scheduler.py +0 -0
  24. {rpa_suite-0.9.3 → rpa_suite-1.0.0}/rpa_suite/date/__init__.py +0 -0
  25. {rpa_suite-0.9.3 → rpa_suite-1.0.0}/rpa_suite/email/__init__.py +0 -0
  26. {rpa_suite-0.9.3 → rpa_suite-1.0.0}/rpa_suite/file/__init__.py +0 -0
  27. {rpa_suite-0.9.3 → rpa_suite-1.0.0}/rpa_suite/file/temp_dir.py +0 -0
  28. {rpa_suite-0.9.3 → rpa_suite-1.0.0}/rpa_suite/log/__init__.py +0 -0
  29. {rpa_suite-0.9.3 → rpa_suite-1.0.0}/rpa_suite/regex/__init__.py +0 -0
  30. {rpa_suite-0.9.3 → rpa_suite-1.0.0}/rpa_suite/validate/__init__.py +0 -0
  31. {rpa_suite-0.9.3 → rpa_suite-1.0.0}/rpa_suite/validate/mail_validator.py +0 -0
  32. {rpa_suite-0.9.3 → rpa_suite-1.0.0}/rpa_suite/validate/string_validator.py +0 -0
  33. {rpa_suite-0.9.3 → rpa_suite-1.0.0}/rpa_suite.egg-info/dependency_links.txt +0 -0
  34. {rpa_suite-0.9.3 → rpa_suite-1.0.0}/rpa_suite.egg-info/top_level.txt +0 -0
  35. {rpa_suite-0.9.3 → rpa_suite-1.0.0}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: rpa_suite
3
- Version: 0.9.3
3
+ Version: 1.0.0
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
@@ -22,6 +22,7 @@ License-File: LICENSE
22
22
  Requires-Dist: loguru
23
23
  Requires-Dist: colorama
24
24
  Requires-Dist: email_validator
25
+ Requires-Dist: colorlog
25
26
 
26
27
  ![RPA Suite](https://raw.githubusercontent.com/CamiloCCarvalho/rpa_suite/3e1ccd0acad654916466f03c2b8f166dc8d360d4/logo-rpa-suite.svg)
27
28
 
@@ -126,6 +127,7 @@ No setup do nosso projeto já estão inclusas as dependências, só será necess
126
127
  - colorama
127
128
  - loguru
128
129
  - email-validator
130
+ - colorlog
129
131
 
130
132
  ## Estrutura do módulo
131
133
  O módulo principal do rpa-suite é dividido em categorias. Cada categoria contém módulos com funções destinadas a cada tipo de tarefa
@@ -141,7 +143,7 @@ O módulo principal do rpa-suite é dividido em categorias. Cada categoria cont
141
143
  - **counter** - Funções para contagem de arquivos
142
144
  - **temp_dir** - Funções para diretórios temporários
143
145
  - **log**
144
- - **loggin** - Funções decoradoras com log de execução das funções
146
+ - **logger** - Objeto de log, cria diretório/arquivo de log integrado aos prints
145
147
  - **printer** - Funções print personalizados (alerta, erro, sucesso, informativo)
146
148
  - **regex**
147
149
  - **list_from_text** - Funções para gerar listas, dividindo texto usando padrão regex
@@ -150,7 +152,7 @@ O módulo principal do rpa-suite é dividido em categorias. Cada categoria cont
150
152
  - **string_validator** - Funções para validação/varredura (strings, substrings, palavras)
151
153
 
152
154
  ## Release
153
- Versão: **Alpha 0.9.3**
155
+ Versão: **Beta 1.0.0**
154
156
 
155
157
  Lançamento: *20/02/2024*
156
158
 
@@ -101,6 +101,7 @@ No setup do nosso projeto já estão inclusas as dependências, só será necess
101
101
  - colorama
102
102
  - loguru
103
103
  - email-validator
104
+ - colorlog
104
105
 
105
106
  ## Estrutura do módulo
106
107
  O módulo principal do rpa-suite é dividido em categorias. Cada categoria contém módulos com funções destinadas a cada tipo de tarefa
@@ -116,7 +117,7 @@ O módulo principal do rpa-suite é dividido em categorias. Cada categoria cont
116
117
  - **counter** - Funções para contagem de arquivos
117
118
  - **temp_dir** - Funções para diretórios temporários
118
119
  - **log**
119
- - **loggin** - Funções decoradoras com log de execução das funções
120
+ - **logger** - Objeto de log, cria diretório/arquivo de log integrado aos prints
120
121
  - **printer** - Funções print personalizados (alerta, erro, sucesso, informativo)
121
122
  - **regex**
122
123
  - **list_from_text** - Funções para gerar listas, dividindo texto usando padrão regex
@@ -125,7 +126,7 @@ O módulo principal do rpa-suite é dividido em categorias. Cada categoria cont
125
126
  - **string_validator** - Funções para validação/varredura (strings, substrings, palavras)
126
127
 
127
128
  ## Release
128
- Versão: **Alpha 0.9.3**
129
+ Versão: **Beta 1.0.0**
129
130
 
130
131
  Lançamento: *20/02/2024*
131
132
 
@@ -8,7 +8,7 @@ def exec_at_hour(
8
8
  fn_to_exec: Callable[..., Any],
9
9
  *args,
10
10
  **kwargs,
11
- ) -> dict:
11
+ ) -> dict[str, bool]:
12
12
 
13
13
  """
14
14
  Timed function, executes the function at the specified time, by ``default`` it executes at runtime, optionally you can choose the time for execution.
@@ -65,35 +65,18 @@ def exec_at_hour(
65
65
  minutes: str
66
66
  moment_now: str
67
67
 
68
- # Preprocessing
69
- run = True
70
- now = dt.now()
71
- hours = str(now.hour) if now.hour > 10 else f"0{now.hour}"
72
- minutes = str(now.minute) if now.minute > 10 else f"0{now.minute}"
73
- moment_now = f'{hours}:{minutes}'
74
-
75
- if hour_to_exec == None:
68
+ try:
69
+ # Preprocessing
70
+ run = True
71
+ now = dt.now()
72
+ hours = str(now.hour) if now.hour > 10 else f"0{now.hour}"
73
+ minutes = str(now.minute) if now.minute > 10 else f"0{now.minute}"
74
+ moment_now = f'{hours}:{minutes}'
76
75
 
77
- # Process
78
- while run:
79
- try:
80
- fn_to_exec(*args, **kwargs)
81
- run = False
82
- result['tried'] = not run
83
- result['success'] = True
84
- success_print(f'{fn_to_exec.__name__}: Successfully executed!')
85
- break
86
-
87
- except Exception as e:
88
- run = False
89
- result['tried'] = not run
90
- result['success'] = False
91
- error_print(f'An error occurred that prevented the function from executing: {fn_to_exec.__name__} correctly. Error: {str(e)}')
92
- break
93
- else:
94
- # Executes the function call only at the time provided in the argument.
95
- while run:
96
- if moment_now == hour_to_exec:
76
+ if hour_to_exec == None:
77
+
78
+ # Process
79
+ while run:
97
80
  try:
98
81
  fn_to_exec(*args, **kwargs)
99
82
  run = False
@@ -108,11 +91,35 @@ def exec_at_hour(
108
91
  result['success'] = False
109
92
  error_print(f'An error occurred that prevented the function from executing: {fn_to_exec.__name__} correctly. Error: {str(e)}')
110
93
  break
111
- else:
112
- time.sleep(30)
113
- now = dt.now()
114
- hours = str(now.hour) if now.hour > 10 else f"0{now.hour}"
115
- minutes = str(now.minute) if now.minute > 10 else f"0{now.minute}"
116
- moment_now = f'{hours}:{minutes}'
94
+ else:
95
+ # Executes the function call only at the time provided in the argument.
96
+ while run:
97
+ if moment_now == hour_to_exec:
98
+ try:
99
+ fn_to_exec(*args, **kwargs)
100
+ run = False
101
+ result['tried'] = not run
102
+ result['success'] = True
103
+ success_print(f'{fn_to_exec.__name__}: Successfully executed!')
104
+ break
105
+
106
+ except Exception as e:
107
+ run = False
108
+ result['tried'] = not run
109
+ result['success'] = False
110
+ error_print(f'An error occurred that prevented the function from executing: {fn_to_exec.__name__} correctly. Error: {str(e)}')
111
+ break
112
+ else:
113
+ time.sleep(30)
114
+ now = dt.now()
115
+ hours = str(now.hour) if now.hour > 10 else f"0{now.hour}"
116
+ minutes = str(now.minute) if now.minute > 10 else f"0{now.minute}"
117
+ moment_now = f'{hours}:{minutes}'
117
118
 
118
- return result
119
+ return result
120
+
121
+ except Exception as e:
122
+
123
+ result['success'] = False
124
+ error_print(f'An error occurred on function from executing: {fn_to_exec.__name__}. Error: {str(e)}')
125
+ return result
@@ -7,7 +7,7 @@ def wait_for_exec(
7
7
  fn_to_exec: Callable[..., Any],
8
8
  *args,
9
9
  **kwargs
10
- ) -> dict:
10
+ ) -> dict[str, bool]:
11
11
 
12
12
  """
13
13
  Timer function, wait for a value in ``seconds`` to execute the function of the argument.
@@ -74,7 +74,7 @@ def exec_and_wait(
74
74
  fn_to_exec: Callable[..., Any],
75
75
  *args,
76
76
  **kwargs
77
- ) -> dict:
77
+ ) -> dict[str, bool]:
78
78
 
79
79
  """
80
80
  Timer function, executes a function and waits for the time in ``seconds``
@@ -1,9 +1,10 @@
1
1
  import datetime as dt
2
+ from typing import Optional as Op
3
+ from typing import Tuple
2
4
  from rpa_suite.log.printer import error_print
3
5
 
4
6
 
5
-
6
- def get_hms() -> tuple:
7
+ def get_hms() -> Tuple[Op[str], Op[str], Op[str]]:
7
8
 
8
9
  """
9
10
  Function to return hour, minute and second. The return is in the form of a tuple with strings being able to store and use the values individually.
@@ -63,10 +64,14 @@ def get_hms() -> tuple:
63
64
  hours[1:]
64
65
 
65
66
  return hours, minutes, seconds
67
+
66
68
  except Exception as e:
67
- return error_print(f'Unable to capture the time. Error: {str(e)}')
68
69
 
69
- def get_dma() -> tuple:
70
+ error_print(f'Unable to capture the time. Error: {str(e)}')
71
+ return None, None, None
72
+
73
+
74
+ def get_dma() -> Tuple[Op[str], Op[str], Op[str]]:
70
75
  """
71
76
  Function to return day, month and year. The return is in the form of a tuple with strings being able to store and use the values individually.
72
77
 
@@ -112,4 +117,6 @@ def get_dma() -> tuple:
112
117
  return day_got, month_got, year_got
113
118
 
114
119
  except Exception as e:
115
- return error_print(f'Unable to capture the time. Error: {str(e)}')
120
+
121
+ error_print(f'Unable to capture the time. Error: {str(e)}')
122
+ return None, None, None
@@ -122,6 +122,7 @@ def send_email(
122
122
 
123
123
  # Add Attachment
124
124
  if attachments:
125
+ result['qt_attach'] = 0
125
126
  result['attchament'] = True
126
127
  for path_to_attach in attachments:
127
128
  file_name = os.path.basename(path_to_attach)
@@ -170,7 +171,7 @@ def send_email(
170
171
  server_by_smtp.quit()
171
172
  result['success'] = True
172
173
  success_print(f'Email(s) Sent!')
173
-
174
+
174
175
 
175
176
  except smtplib.SMTPException as e:
176
177
  result['success'] = False
@@ -1,53 +1,53 @@
1
1
  import os
2
+ from typing import Dict, List, Union
2
3
  from rpa_suite.log.printer import error_print, success_print
3
4
 
5
+
4
6
  def count_files(
5
- dir_to_count: list[str],
6
- type_extension: str = '*'
7
- ) -> dict:
8
-
7
+ dir_to_count: List[str],
8
+ type_extension: str = '*'
9
+ ) -> Dict[str, Union[bool, int]]:
10
+
9
11
  """
10
12
  Function responsible for counting files within a folder, considers subfolders to do the count, searches by file type, being all files by default. \n
11
-
13
+
12
14
  Parameters:
13
15
  ----------
14
16
  ``dir_to_count: list`` - should be a list, accepts more than one path to count files.
15
17
  ``type_extension: str`` - should be a string with the format/extension of the type of file you want to be searched for counting, if empty by default will be used ``*`` which will count all files.
16
18
 
17
-
18
19
  Return:
19
20
  ----------
20
21
  >>> type:dict
21
22
  * 'success': bool - represents if the action was performed successfully
22
23
  * 'qt': int - number that represents the quantity of files that were counted
23
-
24
+
24
25
  Description: pt-br
25
26
  ----------
26
27
  Função responsavel por fazer a contagem de arquivos dentro de uma pasta, considera subpastas para fazer a contagem, busca por tipo de arquivo, sendo todos arquivos por default. \n
27
-
28
+
28
29
  Parametros:
29
30
  ----------
30
31
  ``dir_to_count: list`` - deve ser uma lista, aceita mais de um caminho para contar arquivos.
31
32
  ``type_extension: str`` - deve ser uma string com o formato/extensão do tipo de arquivo que deseja ser buscado para contagem, se vazio por default sera usado ``*`` que contará todos arquivos.
32
33
 
33
-
34
34
  Retorno:
35
35
  ----------
36
36
  >>> type:dict
37
37
  * 'success': bool - representa se ação foi realizada com sucesso
38
38
  * 'qt': int - numero que representa a quantidade de arquivos que foram contados
39
39
  """
40
-
40
+
41
41
  # Local Variables
42
42
  result: dict = {
43
43
  'success': bool,
44
44
  'qt': int
45
45
  }
46
-
46
+
47
47
  # Preprocessing
48
- result['qt'] = 0
49
48
  result['success'] = False
50
-
49
+ result['qt'] = 0
50
+
51
51
  # Process
52
52
  try:
53
53
  for dir in dir_to_count:
@@ -57,9 +57,10 @@ def count_files(
57
57
  result['qt'] += 1
58
58
  result['success'] = True
59
59
  success_print(f'Function: {count_files.__name__} counted {result["qt"]} files.')
60
-
60
+
61
61
  except Exception as e:
62
62
  result['success'] = False
63
63
  error_print(f'Error when trying to count files! Error: {str(e)}')
64
-
65
- return result
64
+
65
+ finally:
66
+ return result
@@ -0,0 +1,81 @@
1
+ import os
2
+ from typing import Union
3
+ from rpa_suite.log.printer import error_print, alert_print, success_print
4
+
5
+
6
+ def _create_log_dir(path_to_create: str = 'default', name_log_dir: str='logs') -> dict[str, Union[bool, str, None]]:
7
+
8
+ """
9
+ Function responsible for creating a logger directory to work with files ``.log``. \n
10
+
11
+ Parameters:
12
+ ----------
13
+ ``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.
14
+
15
+ ``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.
16
+
17
+ Return:
18
+ ----------
19
+ >>> type:dict
20
+ * 'success': bool - represents case the action was performed successfully
21
+ * 'path_created': str - path of the directory that was created on the process
22
+
23
+ Description: pt-br
24
+ ----------
25
+ Função responsavel por criar diretório de logger para trabalhar com arquivos de log. \n
26
+
27
+ Parametros:
28
+ ----------
29
+ ``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.
30
+
31
+ ``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.
32
+
33
+ Retorno:
34
+ ----------
35
+ >>> type:dict
36
+ * 'success': bool - representa se ação foi realizada com sucesso
37
+ * 'path_created': str - path do diretório que foi criado no processo
38
+ """
39
+
40
+ # Local Variables
41
+ result: dict = {
42
+ 'success': bool,
43
+ 'path_created': str,
44
+ }
45
+
46
+ try:
47
+ # by 'default', defines path to local script execution path
48
+ if path_to_create == 'default':
49
+ path_to_create: str = os.getcwd()
50
+
51
+ # Build path to new dir
52
+ full_path: str = os.path.join(path_to_create, name_log_dir)
53
+
54
+ # Create dir in this block
55
+ try:
56
+
57
+ # Successefully created
58
+ os.makedirs(full_path, exist_ok=False)
59
+
60
+ result['success'] = True
61
+ result['path_created'] = fr'{full_path}'
62
+
63
+ success_print(f"Diretório:'{full_path}' foi criado com sucesso.")
64
+
65
+ except FileExistsError:
66
+ result['success'] = False
67
+ result['path_created'] = full_path
68
+ # alert_print(f"Diretório:'{full_path}' já existe.")
69
+
70
+ except PermissionError:
71
+ result['success'] = False
72
+ result['path_created'] = None
73
+ alert_print(f"Permissão negada: não é possível criar o diretório '{full_path}'.")
74
+
75
+ except Exception as e:
76
+ result['success'] = False
77
+ result['path_created'] = None
78
+ error_print(f'Error capturing current path to create logger directory! Error: {str(e)}')
79
+
80
+ finally:
81
+ return result
@@ -0,0 +1,8 @@
1
+ from logging import FileHandler, StreamHandler
2
+ from typing import Optional
3
+
4
+ # Variável global para o manipulador de arquivo
5
+ file_handler: Optional[FileHandler] = None
6
+
7
+ # Variável global para o manipulador de stream stdout/stdin/buffer
8
+ stream_handler: Optional[StreamHandler] = None
@@ -0,0 +1,94 @@
1
+ import logging
2
+ from .logger import file_handler
3
+ from rpa_suite.log.printer import error_print, success_print
4
+
5
+
6
+ def log_start_run_debug(msg_start_loggin: str) -> None: # represent start application
7
+
8
+ """
9
+ Function responsable to generate ``start run log level debug``, in file and print on terminal the same log captured on this call.
10
+ """
11
+
12
+ try:
13
+ global file_handler
14
+ file_handler.stream.write(f'\n{msg_start_loggin}\n')
15
+ success_print(f'{msg_start_loggin}')
16
+
17
+ except Exception as e:
18
+ error_print(f'Erro durante a função: {log_start_run_debug.__name__}! Error: {str(e)}')
19
+
20
+
21
+ def log_debug(msg) -> None:
22
+
23
+ """
24
+ Function responsable to generate log level ``debug``, in file and print on terminal the same log captured on this call.
25
+ """
26
+
27
+ try:
28
+ logging.debug(msg)
29
+
30
+ except Exception as e:
31
+ error_print(f'Erro durante a função: {log_debug.__name__}! Error: {str(e)}')
32
+
33
+ def log_info(msg) -> None:
34
+
35
+ """
36
+ Function responsable to generate log level ``info``, in file and print on terminal the same log captured on this call.
37
+ """
38
+
39
+ try:
40
+ logging.info(msg)
41
+
42
+ except Exception as e:
43
+ error_print(f'Erro durante a função: {log_debug.__name__}! Error: {str(e)}')
44
+
45
+ def log_info(msg) -> None:
46
+
47
+ """
48
+ Function responsable to generate log level ``info``, in file and print on terminal the same log captured on this call.
49
+ """
50
+
51
+ try:
52
+ logging.info(msg)
53
+
54
+ except Exception as e:
55
+ error_print(f'Erro durante a função: {log_info.__name__}! Error: {str(e)}')
56
+
57
+
58
+ def log_warning(msg) -> None:
59
+
60
+ """
61
+ Function responsable to generate log level ``warning``, in file and print on terminal the same log captured on this call.
62
+ """
63
+
64
+ try:
65
+ logging.warning(msg)
66
+
67
+ except Exception as e:
68
+ error_print(f'Erro durante a função: {log_warning.__name__}! Error: {str(e)}')
69
+
70
+
71
+ def log_error(msg) -> None:
72
+
73
+ """
74
+ Function responsable to generate log level ``error``, in file and print on terminal the same log captured on this call.
75
+ """
76
+
77
+ try:
78
+ logging.error(msg)
79
+
80
+ except Exception as e:
81
+ error_print(f'Erro durante a função: {log_error.__name__}! Error: {str(e)}')
82
+
83
+
84
+ def log_critical(msg) -> None:
85
+
86
+ """
87
+ Function responsable to generate log level ``critical``, in file and print on terminal the same log captured on this call.
88
+ """
89
+
90
+ try:
91
+ logging.critical(msg)
92
+
93
+ except Exception as e:
94
+ error_print(f'Erro durante a função: {log_critical.__name__}! Error: {str(e)}')
@@ -4,32 +4,32 @@ from loguru import logger
4
4
  def logging_decorator(
5
5
  fn: Callable
6
6
  ) -> Callable:
7
-
7
+
8
8
  """
9
9
  Function responsible for displaying log message in the console for functions that are called. \n
10
10
  Displays function name, and the result of the function in case of return, without return returns None.
11
-
11
+
12
12
  Return:
13
13
  ----------
14
14
  A ``wrapper`` function with python decoration ``@logger.catch`` that received:
15
15
  * ``*args and **kwargs`` in the call parameters as an argument to result in the Log.
16
-
16
+
17
17
  Description: pt-br
18
18
  ----------
19
19
  Função responsavel por exibir mensagem de log no console para funções que são chamadas. \n
20
20
  Exibe nome da função, e o resultado da função em caso de retorno, sem retorno devolve None.
21
-
21
+
22
22
  Retorno:
23
23
  ----------
24
24
  Uma função ``wrapper`` com decoração ``@logger.catch`` do python que recebeu:
25
25
  * ``*args e **kwargs`` nos parametros de chamada como argumento para resultar no Log.
26
26
  """
27
-
27
+
28
28
  @logger.catch
29
29
  def wrapper(*args, **kwargs):
30
30
  logger.info('Function Called: {}', fn.__name__)
31
31
  result = fn(*args, **kwargs)
32
32
  logger.info('Function {} returned: {}', fn.__name__, result)
33
33
  return result
34
-
34
+
35
35
  return wrapper
@@ -0,0 +1,111 @@
1
+ import logging
2
+ from logging import CRITICAL, ERROR, WARNING, INFO, DEBUG
3
+ from logging import FileHandler, StreamHandler, Filter
4
+ from colorlog import ColoredFormatter
5
+ from typing import Optional as Op
6
+ from ._variables import file_handler, stream_handler
7
+ from .__create_log_dir import _create_log_dir
8
+ from rpa_suite.log.printer import error_print
9
+
10
+
11
+ class Filters(Filter):
12
+
13
+ word_filter: Op[list[str]]
14
+
15
+ def filter(self, record):
16
+
17
+ if len(self.word_filter) > 0:
18
+
19
+ for words in self.word_filter:
20
+
21
+
22
+ string_words: list[str] = [str(word) for word in words]
23
+ """print(words)
24
+ print(type(words))
25
+ print(string_words)
26
+ print(type(string_words))
27
+ input()"""
28
+ for word in string_words:
29
+ if word in record.msg:
30
+ record.msg = 'Log Alterado devido a palavra Filtrada!'
31
+ return True
32
+
33
+ return True
34
+
35
+
36
+ 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]:
37
+
38
+ """
39
+ Function responsible for create a object logger with fileHandler and streamHandler
40
+ """
41
+
42
+ global file_handler, stream_handler
43
+
44
+ try:
45
+
46
+
47
+ if not use_default_path_and_name:
48
+ result_tryed: dict = _create_log_dir(path_dir, name_log_dir)
49
+ path_dir = result_tryed['path_created']
50
+ else:
51
+ if path_dir == None and name_log_dir == None:
52
+ result_tryed: dict = _create_log_dir()
53
+ path_dir = result_tryed['path_created']
54
+
55
+
56
+ # configuração de objetos logger
57
+ file_handler = FileHandler(
58
+ filename=fr'{path_dir}\{name_file_log}.log',
59
+ mode='a',
60
+ encoding='utf-8'
61
+ )
62
+ stream_handler = StreamHandler()
63
+
64
+ # Crie um formatador
65
+ formatter = ColoredFormatter(
66
+ "%(log_color)s%(levelname)s ->%(reset)s %(log_color)s%(message)s%(reset)s",
67
+ datefmt=None,
68
+ reset=True,
69
+ log_colors={
70
+ 'DEBUG': 'cyan',
71
+ 'INFO': 'green',
72
+ 'WARNING': 'yellow',
73
+ 'ERROR': 'red',
74
+ 'CRITICAL': 'red',
75
+ },
76
+ force_color=True
77
+ )
78
+ stream_handler.setFormatter(formatter)
79
+
80
+ # ATRIBUIÇÕES
81
+ new_filter: Op[Filters] = None
82
+ if filter_words is not None:
83
+ new_filter: Filters = Filters()
84
+ new_filter.word_filter = [filter_words]
85
+
86
+ if new_filter is not None:
87
+ file_handler.addFilter(new_filter)
88
+
89
+ file_handler.setLevel(DEBUG)
90
+
91
+ # Obtenha o logger
92
+ logger = logging.getLogger(__name__)
93
+
94
+ # Adicione o manipulador de stream ao logger
95
+ logger.addHandler(stream_handler)
96
+
97
+ # terminando de inplementar configuração para o logger
98
+ FORMAT = '%(levelname)s!%(asctime)s: %(message)s'
99
+ logging.basicConfig(
100
+ level=DEBUG, # level from stream_handler
101
+ #format='%(levelname)s - %(asctime)s - %(message)s',
102
+ format=FORMAT,
103
+ handlers=[file_handler, stream_handler],
104
+ datefmt='%d.%m.%y %H:%M',
105
+ )
106
+ return file_handler
107
+
108
+ except Exception as e:
109
+
110
+ error_print(f'Houve um erro durante a execução da função: {config_logger.__name__}! Error: {str(e)}.')
111
+ return None
@@ -1,4 +1,4 @@
1
- from colorama import Fore, Back, Style
1
+ from colorama import Fore
2
2
 
3
3
  # Windows bash colors
4
4
  class Colors():
@@ -18,29 +18,30 @@ class Colors():
18
18
  def success_print(string_text: str, color=Colors.green, ending="\n") -> None:
19
19
  """
20
20
  Print that indicates ``SUCCESS``. Customized with the color Green \n
21
-
21
+
22
22
  Return:
23
23
  ----------
24
24
  >>> type:None
25
-
25
+
26
26
  pt-br
27
27
  ----------
28
28
  Print que indica ``SUCESSO``. Personalizado com a cor Verde \n
29
-
29
+
30
30
  Retorno:
31
31
  ----------
32
32
  >>> type:None
33
33
  """
34
- return print(f'{color} {string_text} {Colors.default}', end=ending)
34
+ print(f'{color} {string_text} {Colors.default}', end=ending)
35
+
35
36
 
36
37
  def alert_print(string_text: str, color=Colors.yellow, ending="\n") -> None:
37
38
  """
38
39
  Print that indicates ``ALERT``. Customized with the color Yellow \n
39
-
40
+
40
41
  Return:
41
42
  ----------
42
43
  >>> type:None
43
-
44
+
44
45
  pt-br
45
46
  ----------
46
47
  Print que indica ``ALERTA``. Personalizado com a cor Amarelo \n
@@ -48,16 +49,17 @@ def alert_print(string_text: str, color=Colors.yellow, ending="\n") -> None:
48
49
  ----------
49
50
  >>> type:None
50
51
  """
51
- return print(f'{color} {string_text} {Colors.default}', end=ending)
52
+ print(f'{color} {string_text} {Colors.default}', end=ending)
53
+
52
54
 
53
55
  def info_print(string_text: str, color=Colors.cyan, ending="\n") -> None:
54
56
  """
55
57
  Print that indicates ``INFORMATION``. Customized with the color Cyan \n
56
-
58
+
57
59
  Return:
58
60
  ----------
59
61
  >>> type:None
60
-
62
+
61
63
  pt-br
62
64
  ----------
63
65
  Print que indica ``INFORMATIVO``. Personalizado com a cor Ciano \n
@@ -65,16 +67,17 @@ def info_print(string_text: str, color=Colors.cyan, ending="\n") -> None:
65
67
  ----------
66
68
  >>> type:None
67
69
  """
68
- return print(f'{color} {string_text} {Colors.default}', end=ending)
70
+ print(f'{color} {string_text} {Colors.default}', end=ending)
71
+
69
72
 
70
73
  def error_print(string_text: str, color=Colors.red, ending="\n") -> None:
71
74
  """
72
75
  Print that indicates ``ERROR``. Customized with the color Red \n
73
-
76
+
74
77
  Return:
75
78
  ----------
76
79
  >>> type:None
77
-
80
+
78
81
  pt-br
79
82
  ----------
80
83
  Print que indica ``ERRO``. Personalizado com a cor Vermelho \n
@@ -82,16 +85,17 @@ def error_print(string_text: str, color=Colors.red, ending="\n") -> None:
82
85
  ----------
83
86
  >>> type:None
84
87
  """
85
- return print(f'{color} {string_text} {Colors.default}', end=ending)
88
+ print(f'{color} {string_text} {Colors.default}', end=ending)
89
+
86
90
 
87
91
  def magenta_print(string_text: str, color=Colors.magenta, ending="\n") -> None:
88
92
  """
89
93
  Print customized with the color Magenta \n
90
-
94
+
91
95
  Return:
92
96
  ----------
93
97
  >>> type:None
94
-
98
+
95
99
  pt-br
96
100
  ----------
97
101
  Print personalizado com a cor Magenta \n
@@ -99,16 +103,17 @@ def magenta_print(string_text: str, color=Colors.magenta, ending="\n") -> None:
99
103
  ----------
100
104
  >>> type:None
101
105
  """
102
- return print(f'{color} {string_text} {Colors.default}', end=ending)
106
+ print(f'{color} {string_text} {Colors.default}', end=ending)
107
+
103
108
 
104
109
  def blue_print(string_text: str, color=Colors.blue, ending="\n") -> None:
105
110
  """
106
111
  Print customized with the color Blue \n
107
-
112
+
108
113
  Return:
109
114
  ----------
110
115
  >>> type:None
111
-
116
+
112
117
  pt-br
113
118
  ----------
114
119
  Print personalizado com a cor Azul \n
@@ -116,7 +121,8 @@ def blue_print(string_text: str, color=Colors.blue, ending="\n") -> None:
116
121
  ----------
117
122
  >>> type:None
118
123
  """
119
- return print(f'{color} {string_text} {Colors.default}', end=ending)
124
+ print(f'{color} {string_text} {Colors.default}', end=ending)
125
+
120
126
 
121
127
  def print_call_fn(string_text: str, color=Colors.call_fn, ending="\n") -> None:
122
128
  """
@@ -125,7 +131,7 @@ def print_call_fn(string_text: str, color=Colors.call_fn, ending="\n") -> None:
125
131
  Return:
126
132
  ----------
127
133
  >>> type:None
128
-
134
+
129
135
  pt-br
130
136
  ----------
131
137
  Print personalizado para log de chamada de função. \n
@@ -134,7 +140,8 @@ def print_call_fn(string_text: str, color=Colors.call_fn, ending="\n") -> None:
134
140
  ----------
135
141
  >>> type:None
136
142
  """
137
- return print(f'{color} {string_text} {Colors.default}', end=ending)
143
+ print(f'{color} {string_text} {Colors.default}', end=ending)
144
+
138
145
 
139
146
  def print_retur_fn(string_text: str, color=Colors.retur_fn, ending="\n") -> None:
140
147
  """
@@ -143,7 +150,7 @@ def print_retur_fn(string_text: str, color=Colors.retur_fn, ending="\n") -> None
143
150
  Return:
144
151
  ----------
145
152
  >>> type:None
146
-
153
+
147
154
  pt-br
148
155
  ----------
149
156
  Print personalizado para log de chamada de função. \n
@@ -152,4 +159,4 @@ def print_retur_fn(string_text: str, color=Colors.retur_fn, ending="\n") -> None
152
159
  ----------
153
160
  >>> type:None
154
161
  """
155
- return print(f'{color} {string_text} {Colors.default}', end=ending)
162
+ print(f'{color} {string_text} {Colors.default}', end=ending)
@@ -3,9 +3,10 @@ from typing import Any
3
3
  from rpa_suite.log.printer import error_print, success_print
4
4
 
5
5
  def create_list_using_regex(origin_text: str, division_pattern: str) -> list[str] | Any:
6
+
6
7
  """
7
8
  Function responsible for searching in a string ``origin_text`` a pattern ``division_pattern`` and dividing the original text into substrings generating a list of strings, also does the cleaning and treatment to keep the list with the original strings, but divided
8
-
9
+
9
10
  Return:
10
11
  ----------
11
12
  A list of strings divided by the pattern used in the argument passed as a parameter.
@@ -13,11 +14,12 @@ def create_list_using_regex(origin_text: str, division_pattern: str) -> list[str
13
14
  Description: pt-br
14
15
  ----------
15
16
  Função responsável por buscar em um texto de leitura humana uma string ``origin_text`` por um padrão ``division_pattern`` e dividir o texto original em substrings gerando uma lista de strings, também faz a limpeza e tratamento para manter a lista com as strings originais, porem dividas
16
-
17
+
17
18
  Retorno:
18
19
  ----------
19
20
  Uma lista de strings dividas pelo padrão utilizada no argumento passado como parametro.
20
21
  """
22
+
21
23
  try:
22
24
  # creates a delimiter and uses it to split the string based on the pattern
23
25
  text_with_delim = re.sub(division_pattern, r'\1<DELIMITADOR>', origin_text)
@@ -33,11 +35,11 @@ def create_list_using_regex(origin_text: str, division_pattern: str) -> list[str
33
35
  # Removes the delimiter \n both left and right from each element of the list
34
36
  messages_striped = [msg.strip() for i, msg in enumerate(messages)]
35
37
  messages_lstriped = [msg.lstrip() for msg in messages_striped]
36
-
38
+
37
39
  # Removes the delimiter that has been placed between punctuation within the same pattern.
38
40
  messages_final = [msg.replace('\n', ' ') for msg in messages_lstriped]
39
41
  success_print(f'List generated successfully!')
40
42
  return messages_final
41
-
43
+
42
44
  except Exception as e:
43
- return error_print(f"Error when trying to create list using pattern-match (regex). Error: {str(e)}")
45
+ error_print(f"Error when trying to create list using pattern-match (regex). Error: {str(e)}")
@@ -1,72 +1,84 @@
1
+
1
2
  """MODULE CLOCK"""
2
3
  from .clock.waiter import wait_for_exec, exec_and_wait
3
4
  from .clock.exec_at import exec_at_hour
4
5
 
6
+
5
7
  """MODULE DATE"""
6
8
  from .date.date import get_hms, get_dma
7
9
 
10
+
8
11
  """MODULE EMAIL"""
9
12
  from .email.sender_smtp import send_email
10
13
 
14
+
11
15
  """MODULE FILE"""
12
16
  from .file.counter import count_files
13
17
  from .file.temp_dir import create_temp_dir, delete_temp_dir
14
18
 
19
+
15
20
  """MODULE LOG"""
16
21
  # from .log.loggin import logging_decorator
17
22
  from .log.printer import alert_print, success_print, error_print, info_print, print_call_fn, print_retur_fn, magenta_print, blue_print
18
23
 
24
+ from .log.logger import config_logger
25
+ from .log.functions_logger import log_start_run_debug, log_debug, log_info, log_warning, log_error, log_critical
26
+
27
+
19
28
  """MODULE REGEX"""
20
29
  from .regex.list_from_text import create_list_using_regex
21
30
 
31
+
22
32
  """MODULE VALIDATE"""
23
33
  from .validate.mail_validator import valid_emails
24
34
  from .validate.string_validator import search_in
25
35
 
36
+
26
37
  class Rpa_suite():
38
+
27
39
  """
28
40
  The ``Rpa_suite`` class is a generic representation of the modules, with the aim of centralizing all submodules for access through an instance of this representational Object. It contains variables pointed to the functions of the submodules present in the rpa-site.
29
-
41
+
30
42
  Call
31
43
  ----------
32
44
  When calling the maintainer file of this class, an instance of this object will be invoked to be used or reused through another variable
33
-
45
+
34
46
  Objective
35
47
  ----------
36
48
  Flexibility being able to call each submodule individually or by importing the representational object of all submodules.
37
-
49
+
38
50
  Description: pt-br
39
51
  ----------
40
52
  Classe ``Rpa_suite`` é uma representação genérica do dos módulos, com objetivo de centralizar todos submódulos para acesso através de uma instância deste Objeto representacional. Ele contem variaveis apontadas para as funções dos submódulos presentes no rpa-site.
41
-
53
+
42
54
  Chamada
43
55
  ----------
44
56
  Ao chamar o arquivo mantenedor desta classe, sera invocada uma instancia deste objeto para poder ser utilziado ou reutilizado através de outra variável
45
-
57
+
46
58
  Objetivo
47
59
  ----------
48
60
  Flexibilidade podendo chamar cada submódulo de forma individual ou fazendo a importação do objeto representacional de todos submódulos.
49
61
  """
50
-
62
+
51
63
  # clock
52
64
  wait_for_exec = wait_for_exec
53
65
  exec_and_wait = exec_and_wait
54
66
  exec_at_hour = exec_at_hour
55
-
67
+
56
68
  # date
57
69
  get_hms = get_hms
58
70
  get_dma = get_dma
59
-
71
+
60
72
  # email
61
73
  send_email = send_email
62
-
74
+
63
75
  # file
64
76
  count_files = count_files
65
77
  create_temp_dir = create_temp_dir
66
78
  delete_temp_dir = delete_temp_dir
67
79
  #clear_temp_dir = clear_temp_dir
68
-
69
- # log
80
+
81
+ # log - printer
70
82
  alert_print = alert_print
71
83
  success_print = success_print
72
84
  error_print = error_print
@@ -76,18 +88,31 @@ class Rpa_suite():
76
88
  magenta_print = magenta_print
77
89
  blue_print = blue_print
78
90
 
91
+ # log - logger with file and prints
92
+ config_logger = config_logger
93
+ log_start_run_debug = log_start_run_debug
94
+ log_debug = log_debug
95
+ log_info = log_info
96
+ log_warning = log_warning
97
+ log_error = log_error
98
+ log_critical = log_critical
99
+
79
100
  # regex
80
101
  create_list_using_regex = create_list_using_regex
81
-
102
+
82
103
  # validate
83
104
  valid_emails = valid_emails
84
105
  search_in = search_in
85
-
106
+
86
107
  # Create a instance of Rpa_suite
87
108
 
88
109
 
89
110
  # Define function to return this instance
90
- def invoke():
111
+ def invoke() -> Rpa_suite:
112
+
113
+ """
114
+ Function responsible for return a object Rpa_suite with access all modules by .name_module or use 'from rpa_suite import suite' to >>> suite.functions_avaliable()
115
+ """
116
+
91
117
  suite = Rpa_suite()
92
118
  return suite
93
-
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: rpa-suite
3
- Version: 0.9.3
3
+ Version: 1.0.0
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
@@ -22,6 +22,7 @@ License-File: LICENSE
22
22
  Requires-Dist: loguru
23
23
  Requires-Dist: colorama
24
24
  Requires-Dist: email_validator
25
+ Requires-Dist: colorlog
25
26
 
26
27
  ![RPA Suite](https://raw.githubusercontent.com/CamiloCCarvalho/rpa_suite/3e1ccd0acad654916466f03c2b8f166dc8d360d4/logo-rpa-suite.svg)
27
28
 
@@ -126,6 +127,7 @@ No setup do nosso projeto já estão inclusas as dependências, só será necess
126
127
  - colorama
127
128
  - loguru
128
129
  - email-validator
130
+ - colorlog
129
131
 
130
132
  ## Estrutura do módulo
131
133
  O módulo principal do rpa-suite é dividido em categorias. Cada categoria contém módulos com funções destinadas a cada tipo de tarefa
@@ -141,7 +143,7 @@ O módulo principal do rpa-suite é dividido em categorias. Cada categoria cont
141
143
  - **counter** - Funções para contagem de arquivos
142
144
  - **temp_dir** - Funções para diretórios temporários
143
145
  - **log**
144
- - **loggin** - Funções decoradoras com log de execução das funções
146
+ - **logger** - Objeto de log, cria diretório/arquivo de log integrado aos prints
145
147
  - **printer** - Funções print personalizados (alerta, erro, sucesso, informativo)
146
148
  - **regex**
147
149
  - **list_from_text** - Funções para gerar listas, dividindo texto usando padrão regex
@@ -150,7 +152,7 @@ O módulo principal do rpa-suite é dividido em categorias. Cada categoria cont
150
152
  - **string_validator** - Funções para validação/varredura (strings, substrings, palavras)
151
153
 
152
154
  ## Release
153
- Versão: **Alpha 0.9.3**
155
+ Versão: **Beta 1.0.0**
154
156
 
155
157
  Lançamento: *20/02/2024*
156
158
 
@@ -19,8 +19,12 @@ rpa_suite/email/sender_smtp.py
19
19
  rpa_suite/file/__init__.py
20
20
  rpa_suite/file/counter.py
21
21
  rpa_suite/file/temp_dir.py
22
+ rpa_suite/log/__create_log_dir.py
22
23
  rpa_suite/log/__init__.py
23
- rpa_suite/log/loggin.py
24
+ rpa_suite/log/_variables.py
25
+ rpa_suite/log/functions_logger.py
26
+ rpa_suite/log/log_decorator.py
27
+ rpa_suite/log/logger.py
24
28
  rpa_suite/log/printer.py
25
29
  rpa_suite/regex/__init__.py
26
30
  rpa_suite/regex/list_from_text.py
@@ -1,3 +1,4 @@
1
1
  loguru
2
2
  colorama
3
3
  email_validator
4
+ colorlog
@@ -2,7 +2,7 @@ from setuptools import setup, find_packages
2
2
 
3
3
  setup(
4
4
  name='rpa_suite',
5
- version='0.9.3',
5
+ version='1.0.0',
6
6
  packages=find_packages(),
7
7
  description='Conjunto de ferramentas essenciais para Automação RPA com Python, que facilitam o dia a dia de desenvolvimento.',
8
8
  long_description_content_type='text/markdown',
@@ -24,5 +24,5 @@ setup(
24
24
  'Topic :: Software Development :: Libraries :: Python Modules'
25
25
  ],
26
26
  keywords='basic-tools, email-tools, email-validation, file-tools, simple-functions, rpa-tools, rpa-functions, Tools, Rpa, Automation, RPA, Automação, Python, Ferramentas de RPA, Automação de Processos, Biblioteca Python para RPA',
27
- install_requires=['loguru', 'colorama', 'email_validator'],
27
+ install_requires=['loguru', 'colorama', 'email_validator', 'colorlog'],
28
28
  )
File without changes
File without changes