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.
- utils_mystuff/__init__.py +51 -0
- utils_mystuff/convert_regex.py +241 -0
- utils_mystuff/logger_CLI.py +200 -0
- utils_mystuff/utils_GUI.py +442 -0
- utils_mystuff/utils_filehandling.py +204 -0
- utils_mystuff/utils_various.py +461 -0
- utils_mystuff/version.py +55 -0
- utils_mystuff-1.0.0.dist-info/METADATA +82 -0
- utils_mystuff-1.0.0.dist-info/RECORD +12 -0
- utils_mystuff-1.0.0.dist-info/WHEEL +4 -0
- utils_mystuff-1.0.0.dist-info/licenses/AUTHORS.md +3 -0
- utils_mystuff-1.0.0.dist-info/licenses/LICENSE.txt +32 -0
|
@@ -0,0 +1,442 @@
|
|
|
1
|
+
# utilities - GUI related, advanced version with singleton GUI wrapper class to allow switching GUI framework
|
|
2
|
+
|
|
3
|
+
"""
|
|
4
|
+
Module provides a wrapped access to different GUI frameworks for basic GUI functions (message box etc.).
|
|
5
|
+
Calling is via module routines or a singleton GUI framework wrapper class.
|
|
6
|
+
Supported GUI frameworks are 'easygui', 'pymsgbox', 'freesimplegui' (as FOSS predecessor of 'PySimpleGUI').
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
Example / doctest:
|
|
10
|
+
```
|
|
11
|
+
>>> import utils_mystuff as Utils
|
|
12
|
+
>>>
|
|
13
|
+
>>> # test singleton mechanism
|
|
14
|
+
>>> GUIwrapper2 = Utils.utils_GUI.GUIwrapperClass()
|
|
15
|
+
>>> print(Utils.GUIwrapper == GUIwrapper2)
|
|
16
|
+
True
|
|
17
|
+
>>>
|
|
18
|
+
>>> # test listbox single-select mode
|
|
19
|
+
>>> test1 = Utils.listbox("Single selection test", "Test Listbox", ["option 1", "option 2", "option 3", "option 4"], multiselect=False)
|
|
20
|
+
>>> Utils.alertbox(test1, "Test Listbox - single selection")
|
|
21
|
+
>>>
|
|
22
|
+
>>> # test listbox multi-select mode
|
|
23
|
+
>>> test2 = Utils.listbox("Multiple selection mode test", "Test Listbox", ["option 1", "option 2", "option 3", "option 4"], multiselect=True)
|
|
24
|
+
>>> Utils.alertbox(test2, "Test Listbox - multiple selection")
|
|
25
|
+
>>>
|
|
26
|
+
>>> # test alertbox and inputbox
|
|
27
|
+
>>> Utils.alertbox("Test alert text", "Alert Title")
|
|
28
|
+
>>> testinput = Utils.inputbox("Test input prompt:", "Input Title")
|
|
29
|
+
>>> if testinput is not None:
|
|
30
|
+
... Utils.alertbox(testinput, "Test input display")
|
|
31
|
+
... else:
|
|
32
|
+
... Utils.alertbox("keine Eingabe!", "Test input display")
|
|
33
|
+
>>>
|
|
34
|
+
>>> # test yes-No
|
|
35
|
+
>>> testYN = Utils.confirmYesNo("Test confirm Yes/No:", "Confirm YN Title", ["Ja", "Nein"])
|
|
36
|
+
>>> Utils.alertbox(testYN, "Test input Display")
|
|
37
|
+
|
|
38
|
+
```
|
|
39
|
+
"""
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
# ruff and mypy per file settings
|
|
43
|
+
#
|
|
44
|
+
# empty lines
|
|
45
|
+
# ruff: noqa: E302, E303
|
|
46
|
+
# naming conventions
|
|
47
|
+
# ruff: noqa: N801, N802, N803, N806, N812, N813, N815, N816, N818, N999
|
|
48
|
+
# boolean-type arguments
|
|
49
|
+
# ruff: noqa: FBT001, FBT002
|
|
50
|
+
# others
|
|
51
|
+
# ruff: noqa: B006, E501, F841, PLW3301, RUF022
|
|
52
|
+
#
|
|
53
|
+
# disable mypy errors
|
|
54
|
+
# - errors occur when attributes of dynamically (re)loaded module(s)
|
|
55
|
+
# - mypy error "Returning Any from function ..."
|
|
56
|
+
# mypy: disable-error-code = "attr-defined, union-attr, no-any-return"
|
|
57
|
+
|
|
58
|
+
# fmt: off
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
|
|
62
|
+
from typing import Any, Union
|
|
63
|
+
|
|
64
|
+
import sys
|
|
65
|
+
import os.path
|
|
66
|
+
import importlib
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
# block direct calling especially wrapper class
|
|
71
|
+
__all__ = ['GUIwrapper', 'set_gui', 'setGUI', 'alertbox', 'confirm_yes_no', 'confirmYesNo', 'inputbox', 'listbox',
|
|
72
|
+
'exit_finished', 'exitFinished'
|
|
73
|
+
]
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
# singleton wrapper class for different GUI frameworks
|
|
78
|
+
class GUIwrapperClass:
|
|
79
|
+
"""
|
|
80
|
+
GUIwrapperClass - singleton wrapper class for different GUI frameworks
|
|
81
|
+
"""
|
|
82
|
+
|
|
83
|
+
_guiID: str = ""
|
|
84
|
+
_gui_module = None
|
|
85
|
+
|
|
86
|
+
# singleton constructor
|
|
87
|
+
def __new__(cls):
|
|
88
|
+
"""
|
|
89
|
+
__new__ - constructor for GUI wrapper class singleton object
|
|
90
|
+
"""
|
|
91
|
+
|
|
92
|
+
if not hasattr(cls, '_instance'):
|
|
93
|
+
cls._instance = super().__new__(cls)
|
|
94
|
+
return cls._instance
|
|
95
|
+
|
|
96
|
+
# set GUI framework
|
|
97
|
+
def setGUI(self, gui: str) -> None:
|
|
98
|
+
"""
|
|
99
|
+
setGUI - set GUI framework
|
|
100
|
+
|
|
101
|
+
currently supported GUI frameworks are 'easygui', 'pymsgbox', 'freesimplegui'
|
|
102
|
+
(as FOSS predecessor of 'PySimpleGUI')
|
|
103
|
+
|
|
104
|
+
Args:
|
|
105
|
+
gui (str): GUI framework selector
|
|
106
|
+
|
|
107
|
+
Raises:
|
|
108
|
+
Exception: Exception if invalid GUI framework selector provided.
|
|
109
|
+
"""
|
|
110
|
+
|
|
111
|
+
if gui != self._guiID:
|
|
112
|
+
if gui.lower() == "easygui":
|
|
113
|
+
self._guiID = gui
|
|
114
|
+
self._gui_module = importlib.import_module("easygui")
|
|
115
|
+
elif gui.lower() == "pymsgbox":
|
|
116
|
+
self._guiID = gui
|
|
117
|
+
self._gui_module = importlib.import_module("pymsgbox")
|
|
118
|
+
# font size adjustment for PyMsgBox
|
|
119
|
+
self._gui_module.PROPORTIONAL_FONT_SIZE = 10
|
|
120
|
+
self._gui_module.TEXT_ENTRY_FONT_SIZE = 10
|
|
121
|
+
elif gui.lower() == "freesimplegui" or gui.lower() == "pysimplegui":
|
|
122
|
+
self._guiID = gui
|
|
123
|
+
self._gui_module = importlib.import_module("FreeSimpleGUI")
|
|
124
|
+
# set theme
|
|
125
|
+
self._gui_module.theme("Default1")
|
|
126
|
+
else:
|
|
127
|
+
err_msg = "GUI parameter invalid."
|
|
128
|
+
raise Exception(err_msg)
|
|
129
|
+
|
|
130
|
+
def set_gui(self, gui: str) -> None:
|
|
131
|
+
"""
|
|
132
|
+
set_gui - set GUI framework
|
|
133
|
+
|
|
134
|
+
currently supported GUI frameworks are 'easygui', 'pymsgbox', 'freesimplegui'
|
|
135
|
+
(as FOSS predecessor of 'PySimpleGUI')
|
|
136
|
+
|
|
137
|
+
Args:
|
|
138
|
+
gui (str): GUI framework selector
|
|
139
|
+
|
|
140
|
+
Raises:
|
|
141
|
+
Exception: Exception if invalid GUI framework selector provided.
|
|
142
|
+
"""
|
|
143
|
+
self.setGUI(gui)
|
|
144
|
+
|
|
145
|
+
# generalized message box for alerts
|
|
146
|
+
def alertbox(self, text: str, title: str = "") -> None:
|
|
147
|
+
"""
|
|
148
|
+
alertbox - display alert box
|
|
149
|
+
|
|
150
|
+
Args:
|
|
151
|
+
text (str): prompt text
|
|
152
|
+
title (str): title for popup. Defaults to empty string.
|
|
153
|
+
"""
|
|
154
|
+
|
|
155
|
+
if title == "":
|
|
156
|
+
title = os.path.basename(sys.argv[0])
|
|
157
|
+
if self._guiID.lower() == "easygui":
|
|
158
|
+
self._gui_module.msgbox(text, title)
|
|
159
|
+
elif self._guiID.lower() == "pymsgbox":
|
|
160
|
+
self._gui_module.alert(text, title)
|
|
161
|
+
elif self._guiID.lower() in {"freesimplegui", "pysimplegui"}:
|
|
162
|
+
# https://github.com/PySimpleGUI/PySimpleGUI/issues/5879
|
|
163
|
+
self._gui_module.popup(text, title=title, drop_whitespace=False, button_justification="LEFT")
|
|
164
|
+
pass
|
|
165
|
+
|
|
166
|
+
# generalized prompt for input
|
|
167
|
+
def inputbox(self, text: str, title: str = "", default: str = "") -> Any:
|
|
168
|
+
"""
|
|
169
|
+
inputbox - input box
|
|
170
|
+
|
|
171
|
+
Args:
|
|
172
|
+
text (str): prompt text
|
|
173
|
+
title (str): title for popup. Defaults to empty string.
|
|
174
|
+
default (str): default value. Defaults to empty string.
|
|
175
|
+
|
|
176
|
+
Returns:
|
|
177
|
+
Any: entered value
|
|
178
|
+
"""
|
|
179
|
+
|
|
180
|
+
if title == "":
|
|
181
|
+
title = os.path.basename(sys.argv[0])
|
|
182
|
+
if self._guiID.lower() == "easygui":
|
|
183
|
+
return self._gui_module.enterbox(text, title, default)
|
|
184
|
+
elif self._guiID.lower() == "pymsgbox":
|
|
185
|
+
return self._gui_module.prompt(text, title, default)
|
|
186
|
+
elif self._guiID.lower() in {"freesimplegui", "pysimplegui"}:
|
|
187
|
+
return self._gui_module.popup_get_text(message=text, title=title, default_text=default)
|
|
188
|
+
|
|
189
|
+
# generalized selection box
|
|
190
|
+
def listbox( # type: ignore
|
|
191
|
+
self,
|
|
192
|
+
text: str,
|
|
193
|
+
title: str = "",
|
|
194
|
+
choices: list[str] = [],
|
|
195
|
+
multiselect: bool = False
|
|
196
|
+
) -> Union[str, list[str]]:
|
|
197
|
+
"""
|
|
198
|
+
listbox - display listbox with single or multiple selection option
|
|
199
|
+
|
|
200
|
+
Args:
|
|
201
|
+
text (str): prompt text
|
|
202
|
+
title (str): title for popup. Defaults to empty string.
|
|
203
|
+
choices (List[str]): choices for listbox. Defaults to [].
|
|
204
|
+
multiselect (bool): flag for multi-select mode. Defaults to False.
|
|
205
|
+
|
|
206
|
+
Returns:
|
|
207
|
+
Union[str, List[str]]: selected option(s)
|
|
208
|
+
"""
|
|
209
|
+
retval: Union[str, list[str]] = "" # dummy assignment for mypy
|
|
210
|
+
|
|
211
|
+
if title == "":
|
|
212
|
+
title = os.path.basename(sys.argv[0])
|
|
213
|
+
if choices == []:
|
|
214
|
+
err_msg = "No choices provided"
|
|
215
|
+
raise Exception(err_msg)
|
|
216
|
+
if self._guiID.lower() == "easygui":
|
|
217
|
+
if multiselect:
|
|
218
|
+
return self._gui_module.multchoicebox(text, title, choices)
|
|
219
|
+
else:
|
|
220
|
+
return self._gui_module.choicebox(text, title, choices)
|
|
221
|
+
elif self._guiID.lower() == "pymsgbox":
|
|
222
|
+
err_msg = "'pymsgbox' does not support listbox. Wrapper aborted."
|
|
223
|
+
raise Exception(err_msg)
|
|
224
|
+
elif self._guiID.lower() in {"freesimplegui", "pysimplegui"}:
|
|
225
|
+
if multiselect:
|
|
226
|
+
selectmode = self._gui_module.LISTBOX_SELECT_MODE_MULTIPLE
|
|
227
|
+
else:
|
|
228
|
+
selectmode = self._gui_module.LISTBOX_SELECT_MODE_SINGLE
|
|
229
|
+
layout = [
|
|
230
|
+
[self._gui_module.Text(text)],
|
|
231
|
+
[self._gui_module.Listbox(
|
|
232
|
+
choices, [0], size=(max(max(map(len, choices)), len(text) + 5) , min(len(choices), 10)),
|
|
233
|
+
key='-LISTBOX-', enable_events=True, bind_return_key=True, select_mode=selectmode
|
|
234
|
+
)],
|
|
235
|
+
[self._gui_module.OK(), self._gui_module.Cancel()]]
|
|
236
|
+
window = self._gui_module.Window(title, layout, finalize=True)
|
|
237
|
+
listbox = window['-LISTBOX-']
|
|
238
|
+
retval = ""
|
|
239
|
+
while True:
|
|
240
|
+
event, values = window.read()
|
|
241
|
+
if event in {self._gui_module.WIN_CLOSED, "Cancel"}:
|
|
242
|
+
retval = [] if multiselect else ""
|
|
243
|
+
break
|
|
244
|
+
elif event == "OK":
|
|
245
|
+
if multiselect:
|
|
246
|
+
retval = values["-LISTBOX-"]
|
|
247
|
+
else:
|
|
248
|
+
try:
|
|
249
|
+
retval = values["-LISTBOX-"][0]
|
|
250
|
+
except BaseException:
|
|
251
|
+
retval = ""
|
|
252
|
+
break
|
|
253
|
+
elif 'LISTBOX':
|
|
254
|
+
pass
|
|
255
|
+
if not multiselect and values["-LISTBOX-"]:
|
|
256
|
+
try:
|
|
257
|
+
retval = values["-LISTBOX-"][0]
|
|
258
|
+
except BaseException:
|
|
259
|
+
retval = ""
|
|
260
|
+
break
|
|
261
|
+
window.close()
|
|
262
|
+
return retval
|
|
263
|
+
|
|
264
|
+
# generalized message box for confirmations
|
|
265
|
+
def confirmYesNo( # type: ignore
|
|
266
|
+
self,
|
|
267
|
+
text: str,
|
|
268
|
+
title: str = "",
|
|
269
|
+
buttons: list = ['Yes', 'No']
|
|
270
|
+
) -> str:
|
|
271
|
+
"""
|
|
272
|
+
confirmYesNo - display simple Yes/No dialog box (optinally with alternative buttons)
|
|
273
|
+
|
|
274
|
+
Args:
|
|
275
|
+
text (str): prompt text
|
|
276
|
+
title (str): title for popup. Defaults to empty string.
|
|
277
|
+
buttons (list): label for buttons. Defaults to ['Yes', 'No'].
|
|
278
|
+
|
|
279
|
+
Returns:
|
|
280
|
+
str: label of pressed button
|
|
281
|
+
"""
|
|
282
|
+
|
|
283
|
+
if title == "":
|
|
284
|
+
title = os.path.basename(sys.argv[0])
|
|
285
|
+
if self._guiID.lower() == "easygui":
|
|
286
|
+
return self._gui_module.buttonbox(text, title, buttons)
|
|
287
|
+
elif self._guiID.lower() == "pymsgbox":
|
|
288
|
+
return self._gui_module.confirm(text, title, buttons)
|
|
289
|
+
elif self._guiID.lower() == "freesimplegui" or self._guiID.lower() == "pysimplegui":
|
|
290
|
+
# return self._gui_module.popup_yes_no(text, title=title)
|
|
291
|
+
return self._gui_module.popup(text, title=title, custom_text=(buttons[0], buttons[1]))
|
|
292
|
+
|
|
293
|
+
def confirm_yes_no(self, text: str, title: str = "", buttons: list = ['Yes', 'No']) -> str:
|
|
294
|
+
"""
|
|
295
|
+
confirm_yes_no - display simple Yes/No dialog box (optinally with alternative buttons)
|
|
296
|
+
|
|
297
|
+
Args:
|
|
298
|
+
text (str): prompt text
|
|
299
|
+
title (str): title for popup. Defaults to empty string.
|
|
300
|
+
buttons (list): label for buttons. Defaults to ['Yes', 'No'].
|
|
301
|
+
|
|
302
|
+
Returns:
|
|
303
|
+
str: label of pressed button
|
|
304
|
+
"""
|
|
305
|
+
return self.confirmYesNo(text, title, buttons)
|
|
306
|
+
|
|
307
|
+
|
|
308
|
+
# initialize GUIwrapper with default GUI framework
|
|
309
|
+
GUIwrapper = GUIwrapperClass()
|
|
310
|
+
GUIwrapper.setGUI("freesimplegui")
|
|
311
|
+
|
|
312
|
+
|
|
313
|
+
# module level caller stubs for GUIwrapperClass singleton object
|
|
314
|
+
|
|
315
|
+
# set GUI framework
|
|
316
|
+
def setGUI(gui: str) -> None:
|
|
317
|
+
"""
|
|
318
|
+
setGUI - caller stub for singleton GUIwrapperClass object method to set GUI framework
|
|
319
|
+
|
|
320
|
+
currently supported GUI frameworks are 'easygui', 'pymsgbox', 'freesimplegui' (as FOSS predecessor of 'PySimpleGUI')
|
|
321
|
+
|
|
322
|
+
Args:
|
|
323
|
+
gui (str): GUI framework selector
|
|
324
|
+
|
|
325
|
+
Raises:
|
|
326
|
+
Exception: Exception if invalid GUI framework selector provided.
|
|
327
|
+
"""
|
|
328
|
+
GUIwrapper.setGUI(gui)
|
|
329
|
+
|
|
330
|
+
def set_gui(gui: str) -> None:
|
|
331
|
+
"""
|
|
332
|
+
set_gui - caller stub for singleton GUIwrapperClass object method to set GUI framework
|
|
333
|
+
|
|
334
|
+
currently supported GUI frameworks are 'easygui', 'pymsgbox', 'freesimplegui' (as FOSS predecessor of 'PySimpleGUI')
|
|
335
|
+
|
|
336
|
+
Args:
|
|
337
|
+
gui (str): GUI framework selector
|
|
338
|
+
|
|
339
|
+
Raises:
|
|
340
|
+
Exception: Exception if invalid GUI framework selector provided.
|
|
341
|
+
"""
|
|
342
|
+
GUIwrapper.setGUI(gui)
|
|
343
|
+
|
|
344
|
+
# generalized message box for alerts
|
|
345
|
+
def alertbox(text: str, title: str = "") -> None:
|
|
346
|
+
"""
|
|
347
|
+
alertbox - caller stub for singleton GUIwrapperClass object method
|
|
348
|
+
|
|
349
|
+
Args:
|
|
350
|
+
text (str): prompt text
|
|
351
|
+
title (str): title for popup. Defaults to empty string.
|
|
352
|
+
"""
|
|
353
|
+
GUIwrapper.alertbox(text, title)
|
|
354
|
+
|
|
355
|
+
# generalized prompt for input
|
|
356
|
+
def inputbox(text: str, title: str = "", default: str = "") -> Any:
|
|
357
|
+
"""
|
|
358
|
+
inputbox - caller stub for singleton GUIwrapperClass object method
|
|
359
|
+
|
|
360
|
+
Args:
|
|
361
|
+
text (str): prompt text
|
|
362
|
+
title (str): title for popup. Defaults to empty string.
|
|
363
|
+
default (str): default value. Defaults to empty string.
|
|
364
|
+
|
|
365
|
+
Returns:
|
|
366
|
+
Any: entered value
|
|
367
|
+
"""
|
|
368
|
+
return GUIwrapper.inputbox(text, title, default)
|
|
369
|
+
|
|
370
|
+
# generalized selection box
|
|
371
|
+
def listbox(
|
|
372
|
+
text: str,
|
|
373
|
+
title: str = "",
|
|
374
|
+
choices: list[str] = [],
|
|
375
|
+
multiselect: bool = False
|
|
376
|
+
) -> Union[str, list[str]]:
|
|
377
|
+
"""
|
|
378
|
+
listbox - caller stub for singleton GUIwrapperClass object method
|
|
379
|
+
|
|
380
|
+
Args:
|
|
381
|
+
text (str): prompt text
|
|
382
|
+
title (str): title for popup. Defaults to empty string.
|
|
383
|
+
choices (List[str]): Choices for listbox. Defaults to [].
|
|
384
|
+
multiselect (bool): Flag for multi-select mode. Defaults to False.
|
|
385
|
+
|
|
386
|
+
Returns:
|
|
387
|
+
Union[str, List[str]]: selected option(s)
|
|
388
|
+
"""
|
|
389
|
+
return GUIwrapper.listbox(text, title, choices, multiselect)
|
|
390
|
+
|
|
391
|
+
# generalized message box for confirmations
|
|
392
|
+
def confirmYesNo(text: str, title: str = "", buttons: list = ['Yes', 'No']) -> str:
|
|
393
|
+
"""
|
|
394
|
+
confirmYesNo - caller stub for singleton GUIwrapperClass object method
|
|
395
|
+
|
|
396
|
+
Args:
|
|
397
|
+
text (str): prompt text
|
|
398
|
+
title (str): title for popup. Defaults to empty string.
|
|
399
|
+
buttons (list): label for buttons. Defaults to ['Yes', 'No'].
|
|
400
|
+
|
|
401
|
+
Returns:
|
|
402
|
+
str: label of pressed button
|
|
403
|
+
"""
|
|
404
|
+
return GUIwrapper.confirmYesNo(text, title, buttons)
|
|
405
|
+
|
|
406
|
+
def confirm_yes_no(text: str, title: str = "", buttons: list = ['Yes', 'No']) -> str:
|
|
407
|
+
"""
|
|
408
|
+
confirm_yes_no - caller stub for singleton GUIwrapperClass object method
|
|
409
|
+
|
|
410
|
+
Args:
|
|
411
|
+
text (str): prompt text
|
|
412
|
+
title (str): title for popup. Defaults to empty string.
|
|
413
|
+
buttons (list): label for buttons. Defaults to ['Yes', 'No'].
|
|
414
|
+
|
|
415
|
+
Returns:
|
|
416
|
+
str: label of pressed button
|
|
417
|
+
"""
|
|
418
|
+
return confirmYesNo(text, title, buttons)
|
|
419
|
+
|
|
420
|
+
|
|
421
|
+
# standard call stubs used throughout programs
|
|
422
|
+
|
|
423
|
+
# template for ready
|
|
424
|
+
def exitFinished(title: str = "") -> None:
|
|
425
|
+
"""
|
|
426
|
+
exitFinished - dummy finished message box.
|
|
427
|
+
|
|
428
|
+
Args:
|
|
429
|
+
title (str): title for message box. Defaults to empty string.
|
|
430
|
+
"""
|
|
431
|
+
msg: str = "Fertig."
|
|
432
|
+
|
|
433
|
+
GUIwrapper.alertbox(msg, title)
|
|
434
|
+
|
|
435
|
+
def exit_finished(title: str = "") -> None:
|
|
436
|
+
"""
|
|
437
|
+
exit_finished - dummy finished message box.
|
|
438
|
+
|
|
439
|
+
Args:
|
|
440
|
+
title (str): title for message box. Defaults to empty string.
|
|
441
|
+
"""
|
|
442
|
+
exitFinished(title)
|
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
# utilities - files and filesystem related
|
|
2
|
+
|
|
3
|
+
"""
|
|
4
|
+
Module contains filesystem related utilities.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
# ruff and mypy per file settings
|
|
9
|
+
#
|
|
10
|
+
# empty lines
|
|
11
|
+
# ruff: noqa: E302, E303
|
|
12
|
+
# naming conventions
|
|
13
|
+
# ruff: noqa: N801, N802, N803, N806, N812, N813, N815, N816, N818, N999
|
|
14
|
+
# others
|
|
15
|
+
# ruff: noqa: E501 PLR1702 PLW1514 SIM102 SIM115 TID252 UP015
|
|
16
|
+
|
|
17
|
+
# fmt: off
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
from typing import Optional, Union
|
|
22
|
+
|
|
23
|
+
import sys
|
|
24
|
+
import os
|
|
25
|
+
import fnmatch
|
|
26
|
+
import datetime
|
|
27
|
+
import dateutil.tz
|
|
28
|
+
import pytz
|
|
29
|
+
import time
|
|
30
|
+
|
|
31
|
+
from .utils_GUI import alertbox
|
|
32
|
+
|
|
33
|
+
if os.name == "nt" or sys.platform == "win32":
|
|
34
|
+
from .utils_win32 import close_app_windowtitle
|
|
35
|
+
else:
|
|
36
|
+
err_msg = f"No implementation for your platform ('{os.name}') available"
|
|
37
|
+
raise ImportError(err_msg)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
# check if file is locked
|
|
42
|
+
def file_locked(filepath: str, waittime: float = 0.1) -> bool:
|
|
43
|
+
"""
|
|
44
|
+
file_locked - check if file is locked
|
|
45
|
+
|
|
46
|
+
Args:
|
|
47
|
+
filepath (str): file to be checked
|
|
48
|
+
waittime (float, optional): waiting time for check, defaults to 0.1.
|
|
49
|
+
|
|
50
|
+
Returns:
|
|
51
|
+
bool: lock indicator
|
|
52
|
+
"""
|
|
53
|
+
|
|
54
|
+
if not (os.path.exists(filepath)):
|
|
55
|
+
return False
|
|
56
|
+
try:
|
|
57
|
+
f = open(filepath, 'r')
|
|
58
|
+
f.close()
|
|
59
|
+
except OSError:
|
|
60
|
+
return True
|
|
61
|
+
|
|
62
|
+
lockfile = filepath + ".lckchk"
|
|
63
|
+
if os.path.exists(lockfile):
|
|
64
|
+
os.remove(lockfile)
|
|
65
|
+
try:
|
|
66
|
+
os.rename(filepath, lockfile)
|
|
67
|
+
time.sleep(waittime)
|
|
68
|
+
os.rename(lockfile, filepath)
|
|
69
|
+
return False
|
|
70
|
+
except OSError:
|
|
71
|
+
return True
|
|
72
|
+
|
|
73
|
+
def is_file_locked(filepath: str, waittime: float = 0.1) -> bool:
|
|
74
|
+
"""
|
|
75
|
+
is_file_locked - check if file is locked
|
|
76
|
+
|
|
77
|
+
Args:
|
|
78
|
+
filepath (str): file to be checked
|
|
79
|
+
waittime (float, optional): waiting time for check. Defaults to 0.1.
|
|
80
|
+
|
|
81
|
+
Returns:
|
|
82
|
+
bool: lock indicator
|
|
83
|
+
"""
|
|
84
|
+
return file_locked(filepath, waittime)
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
# find latest changed file in searchpath matching filename pattern provided as searchpattern
|
|
88
|
+
# timestamp referring to nanoseconds timestamp from filesystem, otherwise problems in rare cases
|
|
89
|
+
# (1 second resolution not sufficient)
|
|
90
|
+
def find_last_changed_file(
|
|
91
|
+
searchpath: str,
|
|
92
|
+
searchpattern: str,
|
|
93
|
+
searchstart: Optional[datetime.datetime] = None,
|
|
94
|
+
timeout_sec: int = 10
|
|
95
|
+
) -> str:
|
|
96
|
+
"""
|
|
97
|
+
find_last_changed_file - find latest changed file in searchpath matching filename pattern provided as searchpattern
|
|
98
|
+
|
|
99
|
+
Args:
|
|
100
|
+
searchpath (str): path to search in
|
|
101
|
+
searchpattern (str): file pattern
|
|
102
|
+
searchstart (datetime.datetime, optional): search for files changed after 'searchstart' only. Defaults to None.
|
|
103
|
+
timeout_sec (int, optional): timeout period. Defaults to 10.
|
|
104
|
+
|
|
105
|
+
Returns:
|
|
106
|
+
str: name of file found (if any)
|
|
107
|
+
"""
|
|
108
|
+
|
|
109
|
+
timenow = datetime.datetime.now(dateutil.tz.tz.tzlocal())
|
|
110
|
+
if searchstart is None:
|
|
111
|
+
searchstart = timenow - datetime.timedelta(seconds=5)
|
|
112
|
+
if searchstart.tzinfo is None:
|
|
113
|
+
searchstart = pytz.utc.localize(searchstart)
|
|
114
|
+
lastchangedfile = ""
|
|
115
|
+
# lastchangedtimestamp = searchstart - datetime.timedelta(seconds=1)
|
|
116
|
+
lastchangedtimestamp = searchstart.timestamp() - 1
|
|
117
|
+
|
|
118
|
+
while (lastchangedfile == "") and (datetime.datetime.now(dateutil.tz.tz.tzlocal()) <= timenow + datetime.timedelta(seconds=timeout_sec)):
|
|
119
|
+
|
|
120
|
+
with os.scandir(searchpath) as searchpathscan:
|
|
121
|
+
scanentry: os.DirEntry # overcome PyCharm IDE error - workaround derived from https://youtrack.jetbrains.com/issue/PY-46041
|
|
122
|
+
for scanentry in searchpathscan:
|
|
123
|
+
if fnmatch.fnmatch(scanentry.name, searchpattern):
|
|
124
|
+
filemodified = scanentry.stat().st_mtime_ns / 1000000000
|
|
125
|
+
if filemodified >= searchstart.timestamp():
|
|
126
|
+
pathfilename = os.path.join(searchpath, scanentry.name)
|
|
127
|
+
while os.path.isfile(pathfilename) and is_file_locked(pathfilename):
|
|
128
|
+
time.sleep(0.5)
|
|
129
|
+
if os.path.isfile(pathfilename) and not is_file_locked(pathfilename):
|
|
130
|
+
if filemodified > lastchangedtimestamp and scanentry.stat().st_size > 0:
|
|
131
|
+
lastchangedfile = scanentry.name
|
|
132
|
+
lastchangedtimestamp = filemodified
|
|
133
|
+
searchpathscan.close()
|
|
134
|
+
|
|
135
|
+
return lastchangedfile
|
|
136
|
+
|
|
137
|
+
|
|
138
|
+
# load text file
|
|
139
|
+
def load_textfile(txt_filename: str, mode: str = "str") -> Union[list[str], str]:
|
|
140
|
+
"""
|
|
141
|
+
load_textfile - load textfile to list of strings or str
|
|
142
|
+
|
|
143
|
+
Args:
|
|
144
|
+
txt_filename (str): source text file
|
|
145
|
+
mode (str, optional): return mode - 'list', 'str' or 'strcleaned'. Defaults to 'str'.
|
|
146
|
+
|
|
147
|
+
Returns:
|
|
148
|
+
Union[list[str], str]: content of textfile as list of string or string
|
|
149
|
+
"""
|
|
150
|
+
|
|
151
|
+
txt: Union[list[str], str] = ""
|
|
152
|
+
|
|
153
|
+
fileexists = os.path.isfile(txt_filename)
|
|
154
|
+
|
|
155
|
+
# read to list of lines
|
|
156
|
+
if mode == "list":
|
|
157
|
+
if fileexists:
|
|
158
|
+
# via pathlib
|
|
159
|
+
# txt = pathlib.Path(txt_filename).read_text()
|
|
160
|
+
# via normal open file
|
|
161
|
+
with open(txt_filename, "r") as txt_file:
|
|
162
|
+
txt = txt_file.readlines()
|
|
163
|
+
txt_file.close()
|
|
164
|
+
else:
|
|
165
|
+
txt = []
|
|
166
|
+
# read to single string incl. CR
|
|
167
|
+
elif mode == "str":
|
|
168
|
+
if fileexists:
|
|
169
|
+
with open(txt_filename, "r") as txt_file:
|
|
170
|
+
txt = txt_file.read()
|
|
171
|
+
txt_file.close()
|
|
172
|
+
else:
|
|
173
|
+
txt = ""
|
|
174
|
+
# read to single string without CR
|
|
175
|
+
elif mode == "strcleaned":
|
|
176
|
+
if fileexists:
|
|
177
|
+
with open(txt_filename, "r") as txt_file:
|
|
178
|
+
txt = txt_file.read().replace("\n", "")
|
|
179
|
+
txt_file.close()
|
|
180
|
+
else:
|
|
181
|
+
txt = ""
|
|
182
|
+
else:
|
|
183
|
+
err_msg = "Invalid mode."
|
|
184
|
+
raise Exception(err_msg)
|
|
185
|
+
|
|
186
|
+
return txt
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
# close file
|
|
190
|
+
def close_app_file(filename: str, msg: str, title: str) -> None:
|
|
191
|
+
"""
|
|
192
|
+
close_app_file - close data file opened by an application
|
|
193
|
+
|
|
194
|
+
Args:
|
|
195
|
+
filename (str): filename
|
|
196
|
+
msg (str): message for alert box
|
|
197
|
+
title (str): title for alert box
|
|
198
|
+
"""
|
|
199
|
+
|
|
200
|
+
close_app_windowtitle(filename)
|
|
201
|
+
if file_locked(filename):
|
|
202
|
+
close_app_windowtitle(os.path.splitext(os.path.basename(filename))[0])
|
|
203
|
+
while file_locked(filename):
|
|
204
|
+
alertbox(msg, title)
|