utils-mystuff 1.0.0__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.

Potentially problematic release.


This version of utils-mystuff might be problematic. Click here for more details.

@@ -0,0 +1,51 @@
1
+ # utilities
2
+
3
+ """
4
+ Package with various utils i.e. VB regex translation, CLI logging, file handling, ...
5
+
6
+ Set of submodules contains:
7
+
8
+ - submodule for converting Microsoft VB /COM type regular expression to Python regular expression
9
+ - submodule with utilities to log CLI calls of Python scripts
10
+ - submodule with utilities for file handling
11
+ - submodule with wrapper for basic GUI functions for various GUI frameworks
12
+ - submodule with various utilities - read config file with standard parser, set up standard logger object ...
13
+
14
+ Raises:
15
+ ImportError: import error if implementation is not available for platform
16
+ """
17
+
18
+
19
+ # ruff and mypy per file settings
20
+ #
21
+ # empty lines
22
+ # ruff: noqa: E302, E303
23
+ # naming conventions
24
+ # ruff: noqa: N801, N802, N803, N806, N812, N813, N815, N816, N818, N999
25
+ #
26
+ # disable mypy errors
27
+ # mypy: disable-error-code = "assignment"
28
+
29
+ # fmt: off
30
+
31
+
32
+ # version determination
33
+
34
+ # original Hatchlor version
35
+ # from importlib.metadata import PackageNotFoundError, version
36
+ # try:
37
+ # __version__ = version('{{ cookiecutter.project_slug }}')
38
+ # except PackageNotFoundError: # pragma: no cover
39
+ # __version__ = 'unknown'
40
+ # finally:
41
+ # del version, PackageNotFoundError
42
+
43
+ # latest import requirement for hatch-vcs-footgun-example
44
+ from utils_mystuff.version import __version__
45
+
46
+
47
+ from .logger_CLI import *
48
+ from .utils_filehandling import *
49
+ from .utils_GUI import *
50
+ from .utils_various import *
51
+ from .convert_regex import *
@@ -0,0 +1,241 @@
1
+ # utilities - convert RegEx
2
+
3
+ """
4
+ Module provides a converter from Microsoft VB / COM regular expression to Python regular expressions
5
+ to overcome differences in the standard syntax. Basic Eval() functionality is supported as well
6
+ (i.e. basic formatting of found groups/elements).
7
+
8
+ The use case was a flexible file renaming tool including some boolean logic. It was used f. e. to
9
+ assign a report created at the beginning of the following month as report of the previous month.
10
+ Basically, all renaming logic is hidden in regular expressions.
11
+
12
+
13
+ Example / doctest (note escaping in output to avoid error):
14
+ ```
15
+ >>> from utils_mystuff import convertRegExVB2Python
16
+
17
+ >>> # test - conversion
18
+ >>> print(convertRegExVB2Python('"$1_Report_" & $5+($2>$4)*1 & "_" & Format($2, "00") & "_$5$4$3$6"'))
19
+ "\\1_Report_" + str(\\5+(\\2>\\4)*-1) + "_" + "{:02d}".format(\\2) + "_\\5\\4\\3\\6"
20
+ >>> print(convertRegExVB2Python('"$1_Report_" & $2+($3+($4<28)=0) & Format($3+($4<28)-12*($3+($4<28)=0), "00") & "_Korr.pdf"'))
21
+ "\\1_Report_" + str(\\2+(\\3+(\\4<28)*-1==0)*-1) + "{:02d}".format(\\3+(\\4<28)*-1-12*(\\3+(\\4<28)*-1==0)*-1) + "_Korr.pdf"
22
+ >>> print(convertRegExVB2Python("$1_$2"))
23
+ \\1_\\2
24
+ >>> print(convertRegExVB2Python('"$1_Report_" & $5+($2>$4)*1 & "_" & Format($2, "00") & "_$5$4$3$6"'))
25
+ "\\1_Report_" + str(\\5+(\\2>\\4)*-1) + "_" + "{:02d}".format(\\2) + "_\\5\\4\\3\\6"
26
+ >>> print(convertRegExVB2Python('"$1_Report_" & $5+($2>$4)*1 + "_" + Format($2, "00") & "_$5$4$3$6"'))
27
+ "\\1_Report_" + str(\\5+(\\2>\\4)*-1) + "_" + "{:02d}".format(\\2) + "_\\5\\4\\3\\6"
28
+ >>> print(convertRegExVB2Python('"$1$2_Report_" & $3+($4+($5<28)=0) & Format($4+($5<28)-12*($4+($5<28)=0), "00") & "$6"'))
29
+ "\\1\\2_Report_" + str(\\3+(\\4+(\\5<28)*-1==0)*-1) + "{:02d}".format(\\4+(\\5<28)*-1-12*(\\4+(\\5<28)*-1==0)*-1) + "\\6"
30
+
31
+ >>> # test - clean leading zero")
32
+ >>> print(clean_for_eval('"(-1*1*0) + "_" + "{:02d}".format(08) + "_20210901.pdf"'))
33
+ "(-1*1*0) + "_" + "{:02d}".format(8) + "_20210901.pdf"
34
+ >>> print(clean_for_eval('"123456_Report_" + str(2021+(08>09)*-01*1*0) + "_" + "{:02d}".format(08) + "_20210901.pdf"'))
35
+ "123456_Report_" + str(2021+(8>9)*-1*1*0) + "_" + "{:02d}".format(8) + "_20210901.pdf"
36
+ >>> print(clean_for_eval('"123456_Report_" + str(2022+(4+(02<28)*-1==0)*-1) + "{:02d}".format(04+(02<28)*-1-12*(04+(02<28)*-1==0)*-1) + ".pdf"'))
37
+ "123456_Report_" + str(2022+(4+(2<28)*-1==0)*-1) + "{:02d}".format(4+(2<28)*-1-12*(4+(2<28)*-1==0)*-1) + ".pdf"
38
+
39
+ ```
40
+ """
41
+
42
+
43
+ # ruff and mypy per file settings
44
+ #
45
+ # empty lines
46
+ # ruff: noqa: E302, E303
47
+ # naming conventions
48
+ # ruff: noqa: N801, N802, N803, N806, N812, N813, N815, N816, N818, N999
49
+ # boolean-type arguments
50
+ # ruff: noqa: FBT001, FBT002, Q003
51
+ # others
52
+ # ruff: noqa: E501
53
+
54
+ # fmt: off
55
+
56
+
57
+
58
+ # convert Microsoft VB / COM regular expression to Python regular expression
59
+ def convertRegExVB2Python(reVB: str) -> str:
60
+ """
61
+ convertRegExVB2Python - convert Microsoft VB / COM regular expression to Python regular expression
62
+
63
+ Problem: syntax for regular expressions in the Microsoft VB / COM standard is different from Python.
64
+
65
+ Differences in the area of the standard syntax:
66
+
67
+ - for group replacements notation is \\n instead $n
68
+
69
+ Differences if regular expressions are used together with Eval():
70
+
71
+ - different numerical value for True: VB environment = -1, Python = 1
72
+ -> boolean expressions need to be adjusted
73
+ - string concatenation is '&' in VB and '+' in Python
74
+ assumption: '+' is not used for source expressions even allowed
75
+ - '+' may not be applied on int/str in Python
76
+ -> numerical expressions must be bracketed in str()
77
+ - language functions are to be replaced. Implemented:
78
+ "Format" for numerical values
79
+
80
+ Arguments:
81
+ reVB (str): regular expression according to VB / COM standard for Microsoft RegEx engine
82
+
83
+ Returns:
84
+ str: converted regular expression for Python RegEx engine
85
+ """
86
+
87
+ def split_terms(regex: str, quotemark, delim: str = "&+") -> list[str]:
88
+
89
+ terms: list[str] = []
90
+ regex_idx: int = 0
91
+ term_start: int = 0
92
+ quotemark_cnt: int = 0
93
+ bracket_cnt: int = 0
94
+
95
+ regex += " "
96
+ while regex_idx < len(regex):
97
+ if regex[regex_idx] == quotemark:
98
+ quotemark_cnt += 1
99
+ elif regex[regex_idx] in "(){}[]":
100
+ bracket_cnt += 1
101
+ elif (
102
+ (regex[regex_idx] in delim or regex_idx >= len(regex) - 1) and
103
+ quotemark_cnt % 2 == 0 and
104
+ bracket_cnt % 2 == 0
105
+ ):
106
+ term = regex[term_start:regex_idx].strip()
107
+ if (term[-1] in quotemark) or (terms[-1][-1] in quotemark) or (term.lower().find("format(") >= 0):
108
+ terms.append(term)
109
+ else:
110
+ terms[-1] = terms[-1] + "+" + term
111
+ term_start = regex_idx + 1
112
+ regex_idx += 1
113
+
114
+ return terms
115
+
116
+ def convert_other(term: str, embedstr: bool = True) -> str:
117
+
118
+ compare_operator = [">", "<", "="]
119
+ foundbool = False
120
+
121
+ term_idx = 0
122
+ while term_idx < len(term):
123
+ if term[term_idx] in compare_operator:
124
+ if term[term_idx:term_idx + 1] == "<>":
125
+ term = term[:term_idx] + "!=" + term[term_idx + 2:]
126
+ if term[term_idx:term_idx + 1] == "=":
127
+ term = term[:term_idx] + "==" + term[term_idx + 1:]
128
+ term_idx += 1
129
+ while term[term_idx] != ")" and term_idx < len(term):
130
+ term_idx += 1
131
+ if term[term_idx] == ")":
132
+ term = term[0:term_idx] + ")*-1" + term[term_idx + 1:]
133
+ term_idx += 3
134
+ foundbool = True
135
+ elif term_idx == len(term):
136
+ term = "(" + term + ")*-1"
137
+ foundbool = True
138
+ term_idx += 1
139
+
140
+ if foundbool:
141
+ term = term.replace("*-1*1", "*-1").replace("*-1*-1", "*1")
142
+
143
+ if embedstr:
144
+ return "str(" + term + ")"
145
+ else:
146
+ return term
147
+
148
+ def convert_term(term: str, quotemark) -> str:
149
+
150
+ if term[0] == quotemark:
151
+ return term
152
+ elif term.lower()[0:len("format(")] == "format(":
153
+ # only simple integer formatting accepted
154
+ params = term[len("format") + 1:len(term) - 1].split(",")
155
+ params[0] = convert_other(params[0], False)
156
+ return f"\"{{:0{params[1].count('0')}d}}\".format({params[0]})"
157
+ else:
158
+ return convert_other(term)
159
+
160
+ # check quotation mark -> RegEx for use with Eval()
161
+ if reVB[0] == "'":
162
+ quotemark = "'"
163
+ elif reVB[0] == "\"":
164
+ quotemark = "\""
165
+ else:
166
+ quotemark = ""
167
+
168
+ if quotemark != "":
169
+ # top-level split of regular expression into string terms
170
+ terms = split_terms(reVB, quotemark)
171
+ rePy = ""
172
+ for term in terms:
173
+ rePy = convert_term(term, quotemark) if rePy == "" else rePy + " + " + convert_term(term, quotemark)
174
+ else:
175
+ rePy = reVB
176
+
177
+ # replace groups
178
+ for grp_idx in range(9, 0, -1):
179
+ rePy = rePy.replace(f"${grp_idx}", rf"\{grp_idx}")
180
+
181
+ return rePy
182
+
183
+ def convert_regexVB2python(reVB: str) -> str:
184
+ """
185
+ convert_regexVB2python - convert Microsoft VB / COM regular expression to Python regular expression
186
+
187
+ Alternative caller for convertRegExVB2Python. See details there.
188
+
189
+ Arguments:
190
+ reVB (str): regular expression according to VB / COM standard for Microsoft RegEx engine
191
+
192
+ Returns:
193
+ str: converted regular expression for Python RegEx engine
194
+ """
195
+
196
+ return convertRegExVB2Python(reVB)
197
+
198
+ def convert_regexVB_2_python(reVB: str) -> str:
199
+ """
200
+ convert_regexVB_2_python - convert Microsoft VB / COM regular expression to Python regular expression
201
+
202
+ Alternative caller for convertRegExVB2Python. See details there.
203
+
204
+ Arguments:
205
+ reVB (str): regular expression according to VB / COM standard for Microsoft RegEx engine
206
+
207
+ Returns:
208
+ str: converted regular expression for Python RegEx engine
209
+ """
210
+
211
+ return convertRegExVB2Python(reVB)
212
+
213
+
214
+ # clean expression after substitution
215
+ def clean_for_eval(expression: str) -> str:
216
+ """
217
+ clean_for_eval - clean regular expression after substitution
218
+
219
+ delete leading zeros from integer constants to overcome eval() error
220
+
221
+ Arguments:
222
+ expression (str): regular expression to be cleaned
223
+
224
+ Returns:
225
+ str: cleaned regular expression
226
+ """
227
+
228
+ operator_char = [" ", "<", "=", ">", "+", "-", "*", "/", "%", "("]
229
+
230
+ find_start = 0
231
+ for char in operator_char:
232
+ pos = expression.find(f"{char}0")
233
+ while pos >= 0:
234
+ if expression[pos + 2:pos + 3] in "0123456789":
235
+ expression = expression[0:pos + 1] + expression[pos + 2:]
236
+ find_start = pos
237
+ else:
238
+ find_start = pos + 1
239
+ pos = expression.find(f"{char}0", find_start)
240
+
241
+ return expression
@@ -0,0 +1,200 @@
1
+ # utilities - CLI logging facility
2
+
3
+ """
4
+ Module provides CLI logging facility. Logging is possible for CLI arguments and
5
+ parsed arguments structure.
6
+ """
7
+
8
+
9
+ # ruff and mypy per file settings
10
+ #
11
+ # empty lines
12
+ # ruff: noqa: E302, E303
13
+ # naming conventions
14
+ # ruff: noqa: N801, N802, N803, N806, N812, N813, N815, N816, N818, N999
15
+ # others
16
+ # ruff: noqa: E115, E501, RUF059, SIM102
17
+ #
18
+ # disable mypy errors
19
+ # - mypy error "'object' has no attribute 'xyz' [attr-defined]" when accessing attributes of
20
+ # dynamically (re)bound objects
21
+ # mypy: disable-error-code = attr-defined
22
+
23
+ # fmt: off
24
+
25
+
26
+
27
+ import sys
28
+ import os.path
29
+ import tempfile
30
+ import types
31
+ import logging
32
+ import inspect
33
+
34
+
35
+
36
+ # log CLI parameters
37
+
38
+
39
+ # log handler switcher
40
+ # inspired by https://stackoverflow.com/questions/20111758/how-to-insert-newline-in-python-logging
41
+ def _logger_newline_switch_handler(self, how_many_lines: int = 1) -> None:
42
+ """
43
+ log_newline_switch_handler - method for standard logger object to insert empty line
44
+
45
+ Args:
46
+ self (cls): logger, needed as sub is assigned as logger object method.
47
+ how_many_lines (int, optional): number of empty lines. Defaults to 1.
48
+ """
49
+
50
+ # switch handler, output a blank line
51
+ self.removeHandler(self.handler_standard)
52
+ self.addHandler(self.handler_newline)
53
+ # output blank lines
54
+ for i in range(how_many_lines): # noqa: B007
55
+ self.info("")
56
+ # switch back
57
+ self.removeHandler(self.handler_newline)
58
+ self.addHandler(self.handler_standard)
59
+
60
+ def _logger_newline_switch_formatter(self, how_many_lines: int = 1) -> None:
61
+ """
62
+ log_newline_switch_formatter - method for standard logger object to insert empty line
63
+
64
+ Args:
65
+ self (cls): logger, needed as sub is assigned as logger object method.
66
+ how_many_lines (int, optional): number of empty lines. Defaults to 1.
67
+ """
68
+
69
+ # switch handler, output a blank line
70
+ self.handler.setFormatter(self.formatter_blank)
71
+ # output blank lines
72
+ for i in range(how_many_lines): # noqa: B007
73
+ self.info("")
74
+ # switch back
75
+ self.handler.setFormatter(self.formatter_standard)
76
+
77
+
78
+ def setup_CLI_logger(loggerNameCLIlog: str, *, switch_via_handler: bool = False) -> logging.Logger:
79
+ """
80
+ setup_CLI_logger - encapsulated setup of CLI logger object
81
+
82
+ Args:
83
+ loggerNameCLIlog (str): name of logger.
84
+ switch_via_handler (bool): define switching mode. Defaults to False.
85
+
86
+ Returns:
87
+ Logger: logger object
88
+ """
89
+
90
+ # get logger
91
+ loggerCLI = logging.getLogger(loggerNameCLIlog)
92
+
93
+ # log file handler
94
+ # log_filehandler = logging.FileHandler(os.path.join(tempfile.gettempdir(), loggerNameCLIlog + "_Py.txt"))
95
+
96
+ # log formatter - normal & blank line
97
+ formatter_standard = logging.Formatter("%(asctime)s\t%(levelname)s\t%(message)s", datefmt="%d.%m.%Y %H:%M:%S")
98
+ formatter_blank = logging.Formatter(fmt="")
99
+
100
+ if switch_via_handler:
101
+
102
+ # log handler for normal log entries
103
+ # handlerCLI = log_filehandler
104
+ handlerCLI = logging.FileHandler(os.path.join(tempfile.gettempdir(), loggerNameCLIlog + "_Py.txt"))
105
+ handlerCLI.setFormatter(formatter_standard)
106
+ handlerCLI.setLevel(logging.INFO)
107
+
108
+ # log handler for blank lines
109
+ # loghandlerNewline = log_filehandler
110
+ handlerNewline = logging.FileHandler(os.path.join(tempfile.gettempdir(), loggerNameCLIlog + "_Py.txt"))
111
+ handlerNewline.setFormatter(formatter_blank)
112
+ handlerNewline.setLevel(logging.INFO)
113
+
114
+ # set handler for log object
115
+ loggerCLI.addHandler(handlerCLI)
116
+ loggerCLI.setLevel(logging.INFO)
117
+
118
+ # set own switching attributes
119
+ loggerCLI.handler_standard = handlerCLI
120
+ loggerCLI.handler_newline = handlerNewline
121
+ loggerCLI.newline = types.MethodType(_logger_newline_switch_handler, loggerCLI)
122
+
123
+ else:
124
+
125
+ handler = logging.FileHandler(os.path.join(tempfile.gettempdir(), loggerNameCLIlog + "_Py.txt"))
126
+ handler.setFormatter(formatter_standard)
127
+ handler.setLevel(logging.INFO)
128
+
129
+ # set handler for log object
130
+ loggerCLI.addHandler(handler)
131
+ loggerCLI.setLevel(logging.INFO)
132
+
133
+ # set own switching attributes
134
+ loggerCLI.handler = handler
135
+ loggerCLI.formatter_standard = formatter_standard
136
+ loggerCLI.formatter_blank = formatter_blank
137
+ loggerCLI.newline = types.MethodType(_logger_newline_switch_formatter, loggerCLI)
138
+
139
+ return loggerCLI
140
+
141
+
142
+ # init log
143
+ loggerNameCLIlog = "Log_Python_CLI"
144
+ loggerCLI = setup_CLI_logger(loggerNameCLIlog)
145
+
146
+
147
+ # logger routine for args
148
+ def logCLIargs() -> None:
149
+ """
150
+ logCLIargs - write command line interface parameters to specific CLI call log
151
+ """
152
+
153
+ if sys.argv[0] != "-c":
154
+ loggerCLI.info(f"Name Python script: {sys.argv[0]}")
155
+ else:
156
+ stack = inspect.stack()
157
+ loggerCLI.info(
158
+ f"Name Python script: {stack[len(inspect.stack()) - 2].filename} (retrieved from call stack because call using switch -c)"
159
+ )
160
+ argcount = len(sys.argv)
161
+ if argcount > 1:
162
+ for i in range(1, argcount):
163
+ loggerCLI.info(f"Arg {i}: {sys.argv[i]}")
164
+ loggerCLI.info(f"Number of args passed: {argcount - 1}")
165
+ else:
166
+ loggerCLI.info("No args passed.")
167
+ # loggerCLI.info("\n")
168
+ loggerCLI.newline()
169
+
170
+ def log_cli_args() -> None:
171
+ """
172
+ log_cli_args - write command line interface parameters to specific CLI call log
173
+ """
174
+ logCLIargs()
175
+
176
+
177
+ # logger routine for parsed params (should be type dict)
178
+ def logCLIparams(params) -> None:
179
+ """
180
+ logCLIparams - write parsed parameters to specific call log
181
+
182
+ Args:
183
+ params (_type_): params
184
+ """
185
+
186
+ loggerCLI.info("Parsed arguments (from command line or via parameter injected into parse_args):")
187
+ for param in vars(params): # params is NamespaceObject of type TapType and not iterable
188
+ if param in params.class_variables or param in params.argument_buffer:
189
+ loggerCLI.info(f"{param}: {getattr(params, param)}")
190
+ # loggerCLI.info("\n")
191
+ loggerCLI.newline()
192
+
193
+ def log_cli_params(params) -> None:
194
+ """
195
+ log_cli_params - write parsed parameters to specific call log
196
+
197
+ Args:
198
+ params (_type_): params
199
+ """
200
+ logCLIparams(params)