logger-36 2023.13__py3-none-any.whl → 2024.2__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.
Files changed (41) hide show
  1. logger_36/__init__.py +3 -6
  2. logger_36/catalog/config/console_rich.py +49 -0
  3. logger_36/catalog/handler/console.py +80 -0
  4. logger_36/{type/console.py → catalog/handler/console_rich.py} +77 -52
  5. logger_36/catalog/handler/file.py +90 -0
  6. logger_36/catalog/handler/generic.py +150 -0
  7. logger_36/catalog/logging/chronos.py +39 -0
  8. logger_36/catalog/logging/gpu.py +58 -0
  9. logger_36/catalog/logging/memory.py +105 -0
  10. logger_36/catalog/logging/system.py +62 -0
  11. logger_36/config/issue.py +32 -0
  12. logger_36/config/memory.py +33 -0
  13. logger_36/config/message.py +48 -0
  14. logger_36/{config.py → config/system.py} +0 -17
  15. logger_36/constant/generic.py +37 -0
  16. logger_36/constant/handler.py +35 -0
  17. logger_36/constant/issue.py +35 -0
  18. logger_36/{type/file.py → constant/logger.py} +13 -15
  19. logger_36/constant/memory.py +39 -0
  20. logger_36/{constant.py → constant/message.py} +11 -20
  21. logger_36/constant/record.py +35 -0
  22. logger_36/constant/system.py +39 -0
  23. logger_36/instance.py +34 -0
  24. logger_36/main.py +133 -124
  25. logger_36/{measure → task/format}/memory.py +35 -27
  26. logger_36/task/format/message.py +112 -0
  27. logger_36/task/format/rule.py +47 -0
  28. logger_36/task/inspection.py +18 -18
  29. logger_36/{measure → task/measure}/chronos.py +4 -2
  30. logger_36/task/measure/memory.py +50 -0
  31. logger_36/task/storage.py +144 -0
  32. logger_36/type/extension.py +73 -61
  33. logger_36/type/issue.py +57 -0
  34. logger_36/type/logger.py +349 -0
  35. logger_36/version.py +1 -1
  36. {logger_36-2023.13.dist-info → logger_36-2024.2.dist-info}/METADATA +1 -2
  37. logger_36-2024.2.dist-info/RECORD +39 -0
  38. {logger_36-2023.13.dist-info → logger_36-2024.2.dist-info}/WHEEL +1 -1
  39. logger_36/type/generic.py +0 -116
  40. logger_36-2023.13.dist-info/RECORD +0 -16
  41. {logger_36-2023.13.dist-info → logger_36-2024.2.dist-info}/top_level.txt +0 -0
logger_36/main.py CHANGED
@@ -29,157 +29,166 @@
29
29
  # The fact that you are presently reading this means that you have had
30
30
  # knowledge of the CeCILL license and that you accept its terms.
31
31
 
32
- """
33
- Alternative implementations: using logging.Filter or logging.LoggerAdapter.
34
- """
35
32
  import logging as lggg
33
+ import sys as sstm
36
34
  from pathlib import Path as path_t
37
- from typing import Callable, Literal, TextIO
38
35
 
39
- from rich.console import Console as console_t
36
+ try:
37
+ from logger_36.catalog.handler.console_rich import console_rich_handler_t
40
38
 
41
- from logger_36.config import LOGGER_NAME
42
- from logger_36.constant import MAX_DETAIL_NAME_LENGTH, SYSTEM_DETAILS
43
- from logger_36.measure.memory import CanCheckMemory
44
- from logger_36.measure.memory import FormattedUsage as FormattedMemoryUsage
45
- from logger_36.task.inspection import Modules
46
- from logger_36.type.console import console_handler_t
47
- from logger_36.type.file import file_handler_t
48
- from logger_36.type.generic import can_show_message_p, generic_handler_t
39
+ _RICH_ERROR = None
40
+ except ModuleNotFoundError:
41
+ from logger_36.catalog.handler.console import (
42
+ console_handler_t as console_rich_handler_t,
43
+ )
49
44
 
50
- LOGGER = lggg.getLogger(name=LOGGER_NAME)
51
- LOGGER.setLevel(lggg.DEBUG)
52
- LOGGER.addHandler(console_handler_t(level=lggg.INFO))
45
+ _RICH_ERROR = (
46
+ "The Rich console handler is not available, "
47
+ "probably because the Rich package "
48
+ "(https://rich.readthedocs.io/en/stable/index.html) "
49
+ "is not installed, or not loadable. "
50
+ "Falling back to the raw console."
51
+ )
52
+ from logger_36.catalog.handler.console import console_handler_t
53
+ from logger_36.catalog.handler.file import file_handler_t
54
+ from logger_36.catalog.handler.generic import generic_handler_t, interface_h
55
+ from logger_36.constant.handler import HANDLER_CODES, handler_codes_h
56
+ from logger_36.instance import LOGGER
57
+ from logger_36.task.format.message import FormattedMessage
53
58
 
54
59
 
55
- def AddFileHandler(
56
- path: str | path_t, /, *args, level: int = lggg.INFO, **kwargs
60
+ def AddGenericHandler(
61
+ interface: interface_h,
62
+ /,
63
+ *,
64
+ name: str | None = None,
65
+ level: int = lggg.INFO,
66
+ show_where: bool = True,
67
+ show_memory_usage: bool = False,
68
+ formatter: lggg.Formatter | None = None,
69
+ supports_html: bool = False,
70
+ should_hold_messages: bool = False,
71
+ **kwargs,
57
72
  ) -> None:
58
73
  """"""
59
- if isinstance(path, str):
60
- path = path_t(path)
61
- if path.exists():
62
- raise ValueError(f"{path}: File already exists")
74
+ handler = generic_handler_t(
75
+ name=name,
76
+ level=level,
77
+ show_where=show_where,
78
+ show_memory_usage=show_memory_usage,
79
+ formatter=formatter,
80
+ supports_html=supports_html,
81
+ rich_kwargs=kwargs,
82
+ interface=interface,
83
+ )
84
+ LOGGER.AddHandler(handler, should_hold_messages)
85
+
86
+
87
+ def AddConsoleHandler(
88
+ *,
89
+ name: str | None = None,
90
+ level: int = lggg.INFO,
91
+ show_where: bool = True,
92
+ show_memory_usage: bool = False,
93
+ formatter: lggg.Formatter | None = None,
94
+ should_hold_messages: bool = False,
95
+ ) -> None:
96
+ """"""
97
+ handler = console_handler_t(
98
+ name=name,
99
+ level=level,
100
+ show_where=show_where,
101
+ show_memory_usage=show_memory_usage,
102
+ formatter=formatter,
103
+ )
104
+ LOGGER.AddHandler(handler, should_hold_messages)
63
105
 
64
- handler = file_handler_t(path, *args, **kwargs)
65
- handler.setLevel(level)
66
- LOGGER.addHandler(handler)
67
106
 
107
+ def AddRichConsoleHandler(
108
+ *,
109
+ name: str | None = None,
110
+ level: int = lggg.INFO,
111
+ show_where: bool = True,
112
+ show_memory_usage: bool = False,
113
+ formatter: lggg.Formatter | None = None,
114
+ should_hold_messages: bool = False,
115
+ **kwargs,
116
+ ) -> None:
117
+ """"""
118
+ global _RICH_ERROR
119
+ if _RICH_ERROR is not None:
120
+ print(_RICH_ERROR, file=sstm.stderr)
121
+ _RICH_ERROR = None
122
+
123
+ handler = console_rich_handler_t(
124
+ name=name,
125
+ level=level,
126
+ show_where=show_where,
127
+ show_memory_usage=show_memory_usage,
128
+ formatter=formatter,
129
+ rich_kwargs=kwargs,
130
+ )
131
+ LOGGER.AddHandler(handler, should_hold_messages)
68
132
 
69
- def AddGenericHandler(
70
- interface: can_show_message_p | Callable[[str], None],
133
+
134
+ def AddFileHandler(
135
+ path: str | path_t,
71
136
  /,
72
137
  *args,
138
+ name: str | None = None,
73
139
  level: int = lggg.INFO,
74
- supports_html: bool = False,
140
+ show_where: bool = True,
141
+ show_memory_usage: bool = False,
142
+ formatter: lggg.Formatter | None = None,
143
+ should_hold_messages: bool = False,
75
144
  **kwargs,
76
145
  ) -> None:
77
146
  """"""
78
- handler = generic_handler_t(interface, *args, supports_html=supports_html, **kwargs)
79
- handler.setLevel(level)
80
- LOGGER.addHandler(handler)
147
+ if isinstance(path, str):
148
+ path = path_t(path)
149
+ if path.exists():
150
+ raise ValueError(f"File or folder already exists: {path}.")
151
+
152
+ handler = file_handler_t(
153
+ name=name,
154
+ level=level,
155
+ show_where=show_where,
156
+ show_memory_usage=show_memory_usage,
157
+ formatter=formatter,
158
+ path=path,
159
+ handler_args=args,
160
+ handler_kwargs=kwargs,
161
+ )
162
+ LOGGER.AddHandler(handler, should_hold_messages)
81
163
 
82
164
 
83
- def SetLOGLevel(level: int, /, *, which: Literal["c", "f", "a"] = "a") -> None:
165
+ def SetLOGLevel(level: int, /, *, which: handler_codes_h | str = "a") -> None:
84
166
  """
85
- which: c=console, f=file, a=all
167
+ which: g=generic, c=console, f=file, a=all, str=name.
86
168
  """
87
- if which not in "cfa":
88
- raise ValueError(
89
- f"{which}: Invalid handler specifier. "
90
- f'Expected="c" for console, "f" for file, or "a" for all'
91
- )
92
-
169
+ which_is_name = which not in HANDLER_CODES
170
+ found = False
93
171
  for handler in LOGGER.handlers:
94
172
  if (
95
173
  (which == "a")
96
- or ((which == "c") and isinstance(handler, console_handler_t))
174
+ or ((which == "g") and isinstance(handler, generic_handler_t))
175
+ or (
176
+ (which == "c")
177
+ and isinstance(handler, (console_handler_t, console_rich_handler_t))
178
+ )
97
179
  or ((which == "f") and isinstance(handler, file_handler_t))
180
+ or (which == handler.name)
98
181
  ):
99
182
  handler.setLevel(level)
183
+ if which_is_name:
184
+ return
185
+ found = True
100
186
 
101
-
102
- def SetExitOnError(exit_on_error: bool, /) -> None:
103
- """"""
104
- for handler in LOGGER.handlers:
105
- if hasattr(handler, "exit_on_error"):
106
- handler.exit_on_error = exit_on_error
107
-
108
-
109
- def SetShowMemoryUsage(show_memory_usage: bool, /) -> None:
110
- """"""
111
- if show_memory_usage and not CanCheckMemory():
112
- LOGGER.warning('Cannot show memory usage: Package "psutil" not installed')
113
- return
114
-
115
- for handler in LOGGER.handlers:
116
- if hasattr(handler, "show_memory_usage"):
117
- handler.show_memory_usage = show_memory_usage
118
-
119
-
120
- def MaximumUsage(
121
- *, unit: Literal["b", "k", "m", "g", "a"] | None = "a", decimals: int = None
122
- ) -> tuple[int | float, str]:
123
- """
124
- unit: b or None=bytes, k=kilo, m=mega, g=giga, a=auto
125
- """
126
- usage = max(getattr(_hdr, "max_memory_usage", -1) for _hdr in LOGGER.handlers)
127
- return FormattedMemoryUsage(usage, unit=unit, decimals=decimals)
128
-
129
-
130
- def LogSystemDetails() -> None:
131
- """"""
132
- details = "\n".join(
133
- f" {_key:>{MAX_DETAIL_NAME_LENGTH}}: {_vle}"
134
- for _key, _vle in SYSTEM_DETAILS.items()
135
- )
136
-
137
- LOGGER.info(
138
- f"SYSTEM DETAILS\n"
139
- f"{details}\n"
140
- f" {'Python Modules':>{MAX_DETAIL_NAME_LENGTH}}:\n"
141
- f" {Modules(True, True)}"
142
- )
143
-
144
-
145
- def SaveLOGasHTML(path: str | path_t | TextIO = None) -> None:
146
- """"""
147
- cannot_save = "Cannot save logging record as HTML"
148
-
149
- if path is None:
150
- for handler in LOGGER.handlers:
151
- if isinstance(handler, lggg.FileHandler):
152
- path = path_t(handler.baseFilename).with_suffix(".htm")
153
- break
154
- if path is None:
155
- LOGGER.warning(f"{cannot_save}: No file handler to build a filename from.")
156
- return
157
- if path.exists():
158
- LOGGER.warning(
159
- f'{cannot_save}: Automatically generated path "{path}" already exists.'
187
+ if not found:
188
+ raise ValueError(
189
+ FormattedMessage(
190
+ "Handler not found",
191
+ actual=which,
192
+ expected=f"{str(HANDLER_CODES)[1:-1]}, or a handler name",
160
193
  )
161
- return
162
- elif isinstance(path, str):
163
- path = path_t(path)
164
-
165
- actual_file = isinstance(path, path_t)
166
- if actual_file and path.exists():
167
- LOGGER.warning(f'{cannot_save}: File "{path}" already exists.')
168
- return
169
-
170
- console = None
171
- found = False
172
- for handler in LOGGER.handlers:
173
- console = getattr(handler, "console", None)
174
- if found := isinstance(console, console_t):
175
- break
176
-
177
- if found:
178
- html = console.export_html()
179
- if actual_file:
180
- with open(path, "w") as accessor:
181
- accessor.write(html)
182
- else:
183
- path.write(html)
184
- else:
185
- LOGGER.warning(f"{cannot_save}: No handler has a RICH console.")
194
+ )
@@ -29,58 +29,54 @@
29
29
  # The fact that you are presently reading this means that you have had
30
30
  # knowledge of the CeCILL license and that you accept its terms.
31
31
 
32
- from typing import Literal
32
+ from logger_36.constant.memory import STORAGE_UNITS, storage_units_h
33
+ from logger_36.task.format.message import FormattedMessage
33
34
 
34
- try:
35
- from psutil import Process as process_t
35
+ _KILO_UNIT = 1000.0
36
+ _MEGA_UNIT = _KILO_UNIT * 1000.0
37
+ _GIGA_UNIT = _MEGA_UNIT * 1000.0
36
38
 
37
- _PROCESS = process_t()
38
- _KILO_UNIT = 1024.0
39
- _MEGA_UNIT = _KILO_UNIT * 1024.0
40
- _GIGA_UNIT = _MEGA_UNIT * 1024.0
41
- except ModuleNotFoundError:
42
- _PROCESS = None
43
- _KILO_UNIT = _MEGA_UNIT = _GIGA_UNIT = 0.0
44
-
45
-
46
- def CanCheckMemory() -> bool:
47
- """"""
48
- return _PROCESS is not None
49
-
50
-
51
- def CurrentUsage() -> int:
52
- """"""
53
- return _PROCESS.memory_info().rss
39
+ _BLOCKS_PARTIAL = ("", "▏", "▎", "▍", "▌", "▋", "▊")
40
+ _BLOCK_FULL = "▉"
54
41
 
55
42
 
56
43
  def FormattedUsage(
57
44
  usage: int,
58
45
  /,
59
46
  *,
60
- unit: Literal["b", "k", "m", "g", "a"] | None = "a",
47
+ unit: storage_units_h | None = "a",
61
48
  decimals: int = None,
62
49
  ) -> tuple[int | float, str]:
63
50
  """
64
51
  unit: b or None=bytes, k=kilo, m=mega, g=giga, a=auto
65
52
  """
66
53
  if (unit is None) or (unit == "b"):
54
+ value = usage
67
55
  unit = "B"
68
56
  elif unit == "k":
69
- usage = _Rounded(usage / _KILO_UNIT, decimals)
57
+ value = _Rounded(usage / _KILO_UNIT, decimals)
70
58
  unit = "KB"
71
59
  elif unit == "m":
72
- usage = _Rounded(usage / _MEGA_UNIT, decimals)
60
+ value = _Rounded(usage / _MEGA_UNIT, decimals)
73
61
  unit = "MB"
74
62
  elif unit == "g":
75
- usage = _Rounded(usage / _GIGA_UNIT, decimals)
63
+ value = _Rounded(usage / _GIGA_UNIT, decimals)
76
64
  unit = "GB"
77
65
  elif unit == "a":
78
- usage, unit = WithAutoUnit(usage, decimals)
66
+ value, unit = FormattedUsageWithAutoUnit(usage, decimals)
67
+ else:
68
+ raise ValueError(
69
+ FormattedMessage(
70
+ "Invalid unit", actual=unit, expected=str(STORAGE_UNITS)[1:-1]
71
+ )
72
+ )
79
73
 
80
- return usage, unit
74
+ return value, unit
81
75
 
82
76
 
83
- def WithAutoUnit(usage: int, decimals: int | None, /) -> tuple[int | float, str]:
77
+ def FormattedUsageWithAutoUnit(
78
+ usage: int, decimals: int | None, /
79
+ ) -> tuple[int | float, str]:
84
80
  """"""
85
81
  if usage > _GIGA_UNIT:
86
82
  return _Rounded(usage / _GIGA_UNIT, decimals), "GB"
@@ -94,6 +90,18 @@ def WithAutoUnit(usage: int, decimals: int | None, /) -> tuple[int | float, str]
94
90
  return usage, "B"
95
91
 
96
92
 
93
+ def UsageBar(
94
+ usage: int | float, max_usage: int | float, /, *, length_100: int = 10
95
+ ) -> str:
96
+ """"""
97
+ length = (usage / max_usage) * length_100
98
+ n_full_s = int(length)
99
+ return (
100
+ n_full_s * _BLOCK_FULL
101
+ + _BLOCKS_PARTIAL[int((2.0 / 3.0) * int(10 * (length - n_full_s)))]
102
+ )
103
+
104
+
97
105
  def _Rounded(value: float, decimals: int | None, /) -> int | float:
98
106
  """"""
99
107
  if decimals == 0:
@@ -0,0 +1,112 @@
1
+ # Copyright CNRS/Inria/UCA
2
+ # Contributor(s): Eric Debreuve (since 2023)
3
+ #
4
+ # eric.debreuve@cnrs.fr
5
+ #
6
+ # This software is governed by the CeCILL license under French law and
7
+ # abiding by the rules of distribution of free software. You can use,
8
+ # modify and/ or redistribute the software under the terms of the CeCILL
9
+ # license as circulated by CEA, CNRS and INRIA at the following URL
10
+ # "http://www.cecill.info".
11
+ #
12
+ # As a counterpart to the access to the source code and rights to copy,
13
+ # modify and redistribute granted by the license, users are provided only
14
+ # with a limited warranty and the software's author, the holder of the
15
+ # economic rights, and the successive licensors have only limited
16
+ # liability.
17
+ #
18
+ # In this respect, the user's attention is drawn to the risks associated
19
+ # with loading, using, modifying and/or developing or reproducing the
20
+ # software by the user in light of its specific status of free software,
21
+ # that may mean that it is complicated to manipulate, and that also
22
+ # therefore means that it is reserved for developers and experienced
23
+ # professionals having in-depth computer knowledge. Users are therefore
24
+ # encouraged to load and test the software's suitability as regards their
25
+ # requirements in conditions enabling the security of their systems and/or
26
+ # data to be ensured and, more generally, to use and operate it in the
27
+ # same conditions as regards security.
28
+ #
29
+ # The fact that you are presently reading this means that you have had
30
+ # knowledge of the CeCILL license and that you accept its terms.
31
+
32
+ import typing as h
33
+
34
+ from logger_36.config.message import (
35
+ ELAPSED_TIME_FORMAT,
36
+ LEVEL_CLOSING,
37
+ LEVEL_OPENING,
38
+ MEMORY_FORMAT,
39
+ MESSAGE_MARKER,
40
+ )
41
+ from logger_36.constant.generic import NOT_PASSED
42
+ from logger_36.constant.message import EXPECTED_OP, expected_op_h
43
+
44
+
45
+ def MessageFormat(with_where: bool, with_memory_usage: bool, /) -> str:
46
+ """"""
47
+ output = [
48
+ f"%(asctime)s"
49
+ f"{LEVEL_OPENING}%(level_first_letter)s{LEVEL_CLOSING}\t"
50
+ f"{MESSAGE_MARKER}%(message)s"
51
+ ]
52
+
53
+ if with_where:
54
+ output.append("%(where)s")
55
+ output.append(ELAPSED_TIME_FORMAT)
56
+ if with_memory_usage:
57
+ output.append(MEMORY_FORMAT)
58
+
59
+ return "".join(output)
60
+
61
+
62
+ def FormattedMessage(
63
+ message: str,
64
+ /,
65
+ *,
66
+ actual: h.Any = NOT_PASSED,
67
+ expected: h.Any | None = None,
68
+ expected_op: expected_op_h = "=",
69
+ with_final_dot: bool = True,
70
+ ) -> str:
71
+ """"""
72
+ if expected_op not in EXPECTED_OP:
73
+ raise ValueError(
74
+ FormattedMessage(
75
+ 'Invalid "expected" section operator',
76
+ actual=expected_op,
77
+ expected=f"One of {str(EXPECTED_OP)[1:-1]}",
78
+ )
79
+ )
80
+
81
+ if actual is NOT_PASSED:
82
+ if with_final_dot:
83
+ if message[-1] != ".":
84
+ message += "."
85
+ elif message[-1] == ".":
86
+ message = message[:-1]
87
+
88
+ return message
89
+
90
+ if message[-1] == ".":
91
+ message = message[:-1]
92
+ actual = _FormattedValue(actual)
93
+ expected = _FormattedValue(expected)
94
+
95
+ if with_final_dot:
96
+ dot = "."
97
+ else:
98
+ dot = ""
99
+ return f"{message}: Actual={actual}; Expected{expected_op}{expected}{dot}"
100
+
101
+
102
+ def _FormattedValue(value: h.Any, /, *, should_format_str: bool = True) -> str:
103
+ """"""
104
+ if value is None:
105
+ return "None"
106
+
107
+ if isinstance(value, str):
108
+ if should_format_str:
109
+ return f'"{value}"'
110
+ return value
111
+
112
+ return str(value)
@@ -0,0 +1,47 @@
1
+ # Copyright CNRS/Inria/UCA
2
+ # Contributor(s): Eric Debreuve (since 2023)
3
+ #
4
+ # eric.debreuve@cnrs.fr
5
+ #
6
+ # This software is governed by the CeCILL license under French law and
7
+ # abiding by the rules of distribution of free software. You can use,
8
+ # modify and/ or redistribute the software under the terms of the CeCILL
9
+ # license as circulated by CEA, CNRS and INRIA at the following URL
10
+ # "http://www.cecill.info".
11
+ #
12
+ # As a counterpart to the access to the source code and rights to copy,
13
+ # modify and redistribute granted by the license, users are provided only
14
+ # with a limited warranty and the software's author, the holder of the
15
+ # economic rights, and the successive licensors have only limited
16
+ # liability.
17
+ #
18
+ # In this respect, the user's attention is drawn to the risks associated
19
+ # with loading, using, modifying and/or developing or reproducing the
20
+ # software by the user in light of its specific status of free software,
21
+ # that may mean that it is complicated to manipulate, and that also
22
+ # therefore means that it is reserved for developers and experienced
23
+ # professionals having in-depth computer knowledge. Users are therefore
24
+ # encouraged to load and test the software's suitability as regards their
25
+ # requirements in conditions enabling the security of their systems and/or
26
+ # data to be ensured and, more generally, to use and operate it in the
27
+ # same conditions as regards security.
28
+ #
29
+ # The fact that you are presently reading this means that you have had
30
+ # knowledge of the CeCILL license and that you accept its terms.
31
+
32
+
33
+ def RuleAsText(text: str, /) -> str:
34
+ """"""
35
+ return f"---- ---- ---- ---- {text} ---- ---- ---- ----"
36
+
37
+
38
+ try:
39
+ from rich.rule import Rule as rule_t
40
+ from rich.text import Text as text_t
41
+
42
+ def Rule(text: str, color: str, /) -> rule_t:
43
+ """"""
44
+ return rule_t(title=text_t(text, style=f"bold {color}"), style=color)
45
+
46
+ except ModuleNotFoundError:
47
+ Rule = lambda _txt, _: RuleAsText(_txt)
@@ -36,14 +36,15 @@ from types import FunctionType, MethodType
36
36
 
37
37
 
38
38
  def Modules(
39
- with_version: bool, formatted: bool, /, *, only_loaded: bool = True
39
+ with_version: bool, formatted: bool, /, *, only_loaded: bool = True, indent: int = 0
40
40
  ) -> tuple[str, ...] | str:
41
41
  """"""
42
42
  output = []
43
43
 
44
44
  if only_loaded:
45
45
  modules = sstm.modules
46
- module_names = sorted(modules.keys(), key=str.lower)
46
+ module_names = set(modules.keys()).difference(sstm.stdlib_module_names)
47
+ module_names = sorted(module_names, key=str.lower)
47
48
  else:
48
49
  modules = None
49
50
  module_names = _ModulesUsingPkgUtil()
@@ -53,35 +54,34 @@ def Modules(
53
54
  if name.startswith("_") or ("." in name):
54
55
  continue
55
56
 
56
- if modules is None:
57
- version = "?version?"
58
- else:
59
- module = modules[name]
60
- version = getattr(module, "__version__", None)
61
- if version is None:
62
- continue
63
-
64
- if formatted and (m_idx > 0) and (m_idx % 4 == 0):
65
- output.append("\n")
66
-
67
57
  if with_version:
58
+ if modules is None:
59
+ version = "?"
60
+ else:
61
+ module = modules[name]
62
+ # strip: Some packages have a \n at the end of their version. Just in
63
+ # case, let's strip it left and right.
64
+ version = getattr(module, "__version__", "?").strip()
68
65
  element = f"{name}={version}"
69
66
  else:
70
67
  element = name
68
+
69
+ if formatted and (m_idx > 0) and (m_idx % 4 == 0):
70
+ output.append("\n")
71
71
  output.append(element)
72
72
 
73
73
  if formatted:
74
- max_length = max(max_length, name.__len__() + version.__len__() + 1)
74
+ max_length = max(max_length, element.__len__())
75
75
  m_idx += 1
76
76
 
77
77
  if formatted:
78
78
  max_length += 4
79
- AlignedInColumns = (
80
- lambda _str: f"{_str:{max_length}}" if _str != "\n" else "\n "
81
- )
79
+ AlignedInColumns = lambda _str: f"{_str:{max_length}}" if _str != "\n" else "\n"
82
80
  output = map(AlignedInColumns, output)
81
+ output = "".join(output).rstrip()
83
82
 
84
- return "".join(output)
83
+ spaces = indent * " "
84
+ return spaces + f"\n{spaces}".join(map(str.rstrip, output.splitlines()))
85
85
 
86
86
  return tuple(output)
87
87
 
@@ -32,7 +32,9 @@
32
32
  import time
33
33
  from datetime import datetime as dttm
34
34
 
35
- from logger_36.constant import START_TIME
35
+ # This module is imported early. Therefore, the current date and time should be close
36
+ # enough to the real start time of the main script.
37
+ _START_DATE_AND_TIME = dttm.now()
36
38
 
37
39
 
38
40
  def TimeStamp() -> str:
@@ -47,7 +49,7 @@ def TimeStamp() -> str:
47
49
 
48
50
  def ElapsedTime() -> str:
49
51
  """"""
50
- elapsed_seconds = (dttm.now() - START_TIME).total_seconds()
52
+ elapsed_seconds = (dttm.now() - _START_DATE_AND_TIME).total_seconds()
51
53
  output = time.strftime("%Hh %Mm %Ss", time.gmtime(elapsed_seconds))
52
54
  while output.startswith("00") and (" " in output):
53
55
  output = output.split(maxsplit=1)[-1]
@@ -0,0 +1,50 @@
1
+ # Copyright CNRS/Inria/UCA
2
+ # Contributor(s): Eric Debreuve (since 2023)
3
+ #
4
+ # eric.debreuve@cnrs.fr
5
+ #
6
+ # This software is governed by the CeCILL license under French law and
7
+ # abiding by the rules of distribution of free software. You can use,
8
+ # modify and/ or redistribute the software under the terms of the CeCILL
9
+ # license as circulated by CEA, CNRS and INRIA at the following URL
10
+ # "http://www.cecill.info".
11
+ #
12
+ # As a counterpart to the access to the source code and rights to copy,
13
+ # modify and redistribute granted by the license, users are provided only
14
+ # with a limited warranty and the software's author, the holder of the
15
+ # economic rights, and the successive licensors have only limited
16
+ # liability.
17
+ #
18
+ # In this respect, the user's attention is drawn to the risks associated
19
+ # with loading, using, modifying and/or developing or reproducing the
20
+ # software by the user in light of its specific status of free software,
21
+ # that may mean that it is complicated to manipulate, and that also
22
+ # therefore means that it is reserved for developers and experienced
23
+ # professionals having in-depth computer knowledge. Users are therefore
24
+ # encouraged to load and test the software's suitability as regards their
25
+ # requirements in conditions enabling the security of their systems and/or
26
+ # data to be ensured and, more generally, to use and operate it in the
27
+ # same conditions as regards security.
28
+ #
29
+ # The fact that you are presently reading this means that you have had
30
+ # knowledge of the CeCILL license and that you accept its terms.
31
+
32
+ try:
33
+ from psutil import Process as process_t
34
+
35
+ _PROCESS = process_t()
36
+ except ModuleNotFoundError:
37
+ _PROCESS = None
38
+
39
+
40
+ def CanCheckMemory() -> bool:
41
+ """"""
42
+ return _PROCESS is not None
43
+
44
+
45
+ def CurrentUsage() -> int:
46
+ """"""
47
+ if _PROCESS is None:
48
+ return -1
49
+
50
+ return _PROCESS.memory_info().rss