cjnfuncs 2.4__tar.gz → 2.5__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.
@@ -1,6 +1,6 @@
1
- Metadata-Version: 2.1
1
+ Metadata-Version: 2.2
2
2
  Name: cjnfuncs
3
- Version: 2.4
3
+ Version: 2.5
4
4
  Summary: A collection of core functions for tool script writing
5
5
  Author-email: Chris Nelson <github@cjnaz.com>
6
6
  License: MIT License
@@ -75,6 +75,8 @@ Project repo: https://github.com/cjnaz/cjnfuncs
75
75
  <br/>
76
76
 
77
77
  ## Revision history
78
+ - 2.5 250206 - Added multi-line and quoted string support to configman
79
+ - 2.4.1 241118 - resource_lock only init lock_info if not existing
78
80
  - 2.4 241105 - Twilio support in snd_notif, resource_lock trace/debug features, check_path_exists exception fix
79
81
  - 2.3 240821 - Added mungePath ./ support.
80
82
  Resolved check_path_exists() memory leak.
@@ -38,6 +38,8 @@ Project repo: https://github.com/cjnaz/cjnfuncs
38
38
  <br/>
39
39
 
40
40
  ## Revision history
41
+ - 2.5 250206 - Added multi-line and quoted string support to configman
42
+ - 2.4.1 241118 - resource_lock only init lock_info if not existing
41
43
  - 2.4 241105 - Twilio support in snd_notif, resource_lock trace/debug features, check_path_exists exception fix
42
44
  - 2.3 240821 - Added mungePath ./ support.
43
45
  Resolved check_path_exists() memory leak.
@@ -5,14 +5,8 @@ build-backend = "setuptools.build_meta"
5
5
 
6
6
  [project]
7
7
  name = "cjnfuncs"
8
- version = "2.4"
9
- # 2.4 - release
10
- # 2.4rc2 - check_path_exists() exception fix for unmounted network path (OSError: [Errno 19] No such device)
11
- # 2.4rc1 - doc fix on setuplogging()
12
- # 2.4b4 - resourcelock closed attribute
13
- # 2.4b3 - Added lock_info to resource_lock
14
- # 2.4b2 - Added where_called to resource_lock unget for debugging aid
15
- # 2.4b1 - Added Twilio support to snd_notif
8
+ version = "2.5"
9
+ # 2.5 - configman config file parser refactor - multi-line, quoted strings support
16
10
  description = "A collection of core functions for tool script writing"
17
11
  readme = "README.md"
18
12
  requires-python = ">=3.6" # Centos 7 uses 3.6.8
@@ -8,7 +8,6 @@
8
8
  #
9
9
  #==========================================================
10
10
 
11
-
12
11
  import re
13
12
  import ast
14
13
  from pathlib import Path
@@ -21,6 +20,7 @@ import cjnfuncs.core as core
21
20
  DEFAULT_LOGGING_LEVEL = logging.WARNING
22
21
  IO_RETRY_COUNT = 3
23
22
 
23
+
24
24
  #=====================================================================================
25
25
  #=====================================================================================
26
26
  # C l a s s c o n f i g _ i t e m
@@ -28,9 +28,6 @@ IO_RETRY_COUNT = 3
28
28
  #=====================================================================================
29
29
 
30
30
  initial_logging_setup_done = False # Global since more than one config can be loaded
31
- CFGLINE = re.compile(r"([^\s=:]+)[\s=:]*(.*)") # used in load_config() for param:value lines
32
- CFGLINE2 = re.compile(r"(\s*)([^\s=:]+)([\s=:]+)([^#]+)(.*)") # used in modify_configfile()
33
- SECLINE = re.compile(r"\[(.*)\]") # used for getting section names
34
31
 
35
32
 
36
33
  class config_item():
@@ -41,12 +38,13 @@ The config_item() class provides handling of one or more config file instances.
41
38
  - Config file loading and reloading - `loadconfig()`
42
39
  - Loading config data from strings and dictionaries - `read_string()`, `read_dict()`
43
40
  - Getting values from the loaded config, with defaults and fallback - `getcfg()`
44
- - Programmatically modifiying the config file content - `modify_configfile()`
41
+ - Programmatically modifying the config file content - `modify_configfile()`
45
42
  - Getting instance status - `__repr__()`, `section()`, `dump()`
46
43
 
44
+ See the loadconfig() documentation for details on config file syntax and rules.
47
45
 
48
46
  ### Instantiation parameters
49
- `config_file` (str, default None)
47
+ `config_file` (Path or str, default None)
50
48
  - Path to the configuration file, relative to the `core.tool.config_dir` directory, or an absolute path.
51
49
  - `None` may be used if the config will be loaded programmatically via `read_string()` or `read_dict()`.
52
50
 
@@ -63,6 +61,30 @@ then the `core.tool.log_dir_base` will be set to `core.tool.config_dir`.
63
61
  is properly set up.
64
62
 
65
63
 
64
+ ### Useful class attributes
65
+ The current values of all public class attributes may be printed using `print(my_config)`.
66
+
67
+ `.cfg` (dict)
68
+ - Holds all loaded params. May be access directly. Sections are stored as sub-dictionaries of .cfg.
69
+ - The contents of the .cfg dictionary may be printed using `print(my_config.dump())`
70
+
71
+ `.defaults` (dict)
72
+ - Default params are stored here.
73
+
74
+ `.sections_list` (list)
75
+ - A list of string names for all defined sections.
76
+
77
+ `.config_file` (str, or None)
78
+ - The `config_file` as passed in at instantiation
79
+
80
+ `.config_full_path` (Path or None)
81
+ - The full expanduser/expandvars path to the config file, relative to core.tool.config_dir if the
82
+ instantiation `config_file` is a relative path (uses mungePath)
83
+
84
+ `.config_dir` (Path or None)
85
+ - The directory above `.config_full_path`
86
+
87
+
66
88
  ### Returns
67
89
  - Handle to the `config_item()` instance
68
90
  - Raises a `ConfigError` if the specified config file is not found
@@ -72,7 +94,7 @@ is properly set up.
72
94
  - More than one `config_item()` may be created and loaded. This allows for configuration data to be partitioned
73
95
  as desired. Each defined config is loaded to its own instance-specific `cfg` dictionary. Only one config_item()
74
96
  instance should be considered the primary, while other instances should be tagged with `secondary_config=True`.
75
- Logging setups are controlled only the primary instance.
97
+ Logging setups are controlled only by the primary instance.
76
98
  Also see the loadconfig() `import` feature.
77
99
  - Initially in _user_ mode, after the `set_toolname()` call, `core.tool.log_dir_base`
78
100
  (the log directory) is set to the `core.tool.user_data_dir`.
@@ -83,12 +105,12 @@ To disable this remap, in the `config_item()` call set `remap_logdirbase=False`.
83
105
  This remapping is not done in site mode.
84
106
  - A different log base directory may be set by user code by setting `core.tool.log_dir_base` to a different
85
107
  path after the `set_toolname()` call and before the `config_item()` call, for example
86
- `core.tool.log_dir_base = "/var/log"` may be desireable in site mode.
108
+ `core.tool.log_dir_base = "/var/log"` may be desirable in site mode.
87
109
  - A different config directory may be set by user code by setting `core.tool.config_dir` to a different
88
110
  path after the `set_toolname()` call and before the `config_item()` call, for example
89
- `core.tool.config_dir = core.tool.main_dir`, which sets the config dir to the same as the tool script's
111
+ `core.tool.config_dir = core.tool.main_dir` sets the config dir to the same as the tool script's
90
112
  directory. With `remap_logdirbase=True`, the log dir will also be set to the tool script's directory.
91
- - Details of the configuration instance may be printed, eg, `print (my_config)`.
113
+ - Details of the configuration instance may be printed, eg, `print(my_config)`.
92
114
  """
93
115
 
94
116
  def __init__(self, config_file=None, remap_logdirbase=True, force_str=False, secondary_config=False):
@@ -130,153 +152,6 @@ directory. With `remap_logdirbase=True`, the log dir will also be set to the to
130
152
  self.cfg[section_name][key] = value
131
153
 
132
154
 
133
- def _parse_value(self, value_str):
134
- if self.force_str:
135
- return value_str
136
-
137
- try: # Integer
138
- return int(value_str)
139
- except:
140
- pass
141
- try: # Float
142
- return float(value_str)
143
- except:
144
- pass
145
- if value_str.lower() == "true": # Boolean True
146
- return True
147
- if value_str.lower() == "false": # Boolean False
148
- return False
149
- try:
150
- if (value_str.startswith('[') and value_str.endswith(']')) or \
151
- (value_str.startswith('{') and value_str.endswith('}')) or \
152
- (value_str.startswith('(') and value_str.endswith(')')):
153
- return ast.literal_eval(value_str) # List, Dictionary, or Tuple
154
- except:
155
- pass
156
- return value_str # String
157
-
158
-
159
- def _check_section(self, xyz):
160
- out = SECLINE.match(xyz)
161
- if out:
162
- section_name = out.group(1).strip()
163
- if section_name != '' and section_name not in self.sections_list and section_name != 'DEFAULT':
164
- self.cfg[section_name] = {}
165
- self.sections_list.append(section_name)
166
- return section_name
167
- else:
168
- return None
169
-
170
-
171
- #=====================================================================================
172
- #=====================================================================================
173
- # s e c t i o n s
174
- #=====================================================================================
175
- #=====================================================================================
176
-
177
- def sections(self):
178
- """
179
- ## sections () - Return a list of sections in the cfg dictionary
180
-
181
- ***config_item() class member function***
182
-
183
- For compatibility with the standard library configparser. Also available via `<config>.sections_list`.
184
-
185
- Example:
186
- ```
187
- code:
188
- print (my_config.sections())
189
-
190
- output:
191
- ['Bad params', 'SMTP']
192
- ```
193
- """
194
-
195
- return self.sections_list
196
-
197
-
198
- #=====================================================================================
199
- #=====================================================================================
200
- # c l e a r
201
- #=====================================================================================
202
- #=====================================================================================
203
-
204
- def clear(self, section=''):
205
- """
206
- ## clear (section='') - Purge a portion of the cfg dictionary
207
-
208
- ***config_item() class member function***
209
-
210
- ### Parameters
211
- `section` (str, default '')
212
- - `section = ''` clears the entire cfg dictionary, including all sections and DEFAULT
213
- - `section = '<section_name>'` clears just that section
214
- - `section = 'DEFAULT'` clears just the DEFAULT section
215
-
216
-
217
- ### Returns
218
- - A ConfigError is raised if attempting to remove a non-existing section
219
- """
220
-
221
- if section == '':
222
- self.cfg.clear()
223
- self.sections_list = []
224
- self.defaults.clear()
225
- elif section in self.sections_list:
226
- self.cfg.pop(section, None)
227
- self.sections_list.remove(section)
228
- elif section == 'DEFAULT':
229
- self.defaults.clear()
230
- else:
231
- raise ConfigError (f"Failed attempt to remove non-existing section <{section}> from config")
232
-
233
-
234
- #=====================================================================================
235
- #=====================================================================================
236
- # _ _ r e p r _ _
237
- #=====================================================================================
238
- #=====================================================================================
239
-
240
- def __repr__(self):
241
- stats = ""
242
- stats += f"\nStats for config file <{self.config_file}>:\n"
243
- stats += f".config_file : {self.config_file}\n"
244
- stats += f".config_dir : {self.config_dir}\n"
245
- stats += f".config_full_path : {self.config_full_path}\n"
246
- stats += f".config_timestamp : {self.config_timestamp}\n"
247
- stats += f".sections_list : {self.sections_list}\n"
248
- stats += f"core.tool.log_dir_base : {core.tool.log_dir_base}\n"
249
- # stats += f"tool.log_full_path : {tool.log_full_path}\n"
250
- return stats
251
-
252
-
253
- #=====================================================================================
254
- #=====================================================================================
255
- # d u m p
256
- #=====================================================================================
257
- #=====================================================================================
258
-
259
- def dump(self):
260
- """
261
- ## dump () - Return the formatted content of the cfg dictionary
262
-
263
- ***config_item() class member function***
264
- """
265
-
266
- cfg_list = "***** Section [] *****\n"
267
- for key in self.cfg:
268
- if key not in self.sections_list:
269
- cfg_list += f"{key:>20} = {self.cfg[key]} {type(self.cfg[key])}\n"
270
- for section in self.sections_list:
271
- cfg_list += f"***** Section [{section}] *****\n"
272
- for key in self.cfg[section]:
273
- cfg_list += f"{key:>20} = {self.cfg[section][key]} {type(self.cfg[section][key])}\n"
274
- cfg_list += f"***** Section [DEFAULT] *****\n"
275
- for key in self.defaults:
276
- cfg_list += f"{key:>20} = {self.defaults[key]} {type(self.defaults[key])}\n"
277
- return cfg_list[:-1] # drop final '\n'
278
-
279
-
280
155
  #=====================================================================================
281
156
  #=====================================================================================
282
157
  # l o a d c o n f i g
@@ -307,8 +182,9 @@ loadconfig(
307
182
  ```
308
183
  ***config_item() class member function***
309
184
 
310
- Param = value lines in the config_item()'s file are loaded to the instance-specific `cfg` dictionary,
311
- and can be accessed directly or via `<config_item>.getcfg()`.
185
+ `Param = value` lines in the config_item()'s file are loaded to the instance-specific `cfg` dictionary,
186
+ and can be accessed via `<config_item>.getcfg()`. The _value_ is referred to as the _value_portion_ in
187
+ this documentation.
312
188
 
313
189
  `loadconfig()` initializes the root logger for logging either to 1) the `LogFile` specified in
314
190
  the loaded config file, 2) the `call_logfile` in the `loadconfig()` call, or 3) the console.
@@ -320,15 +196,18 @@ feature, and intermittent loss of access to the config file.
320
196
  `ldcfg_ll` (int, default 30 (WARNING))
321
197
  - Logging level used within `loadconfig()` code for debugging loadconfig() itself
322
198
 
323
- `call_logfile` (str, default None)
199
+ `call_logfile` (Path or str, default None)
200
+ - If `call_logfile` is passed on the loadconfig() call, and `call_logfile_wins=True`, then any `LogFile`
201
+ specified in the config file is overridden. This feature allows for interactive usage modes where
202
+ logging is directed to the console (with `call_logfile=None`) or an alternate file.
324
203
  - An absolute path or relative to the `core.tool.log_dir_base` directory
325
204
 
326
205
  `call_logfile_wins` (bool, default False)
327
- - If True, the `call_logfile` overrides any `LogFile` in the config file
206
+ - If True, the `call_logfile` overrides any `LogFile` defined in the config file
328
207
 
329
208
  `flush_on_reload` (bool, default False)
330
209
  - If the config file will be reloaded (due to a changed timestamp) then clean out the
331
- `cfg` dictionary first
210
+ `cfg` dictionary first. See Returns, below.
332
211
 
333
212
  `force_flush_reload` (bool, default False)
334
213
  - Forces the `cfg` dictionary to be cleaned out and the config file to be reloaded,
@@ -358,19 +237,32 @@ regardless of whether the config file timestamp has changed
358
237
  directly accessed as well.
359
238
 
360
239
  - The format of a config file is param=value pairs.
361
- - Separating the param and value may be whitespace, `=` or `:`.
362
- - Param names can contain most all characters, except: `#` or the separators, and cannot start with `[`.
240
+ - Separating the param and value_portion may be whitespace, `=` or `:` (multiples allowed).
241
+ - Param names can contain all valid characters, except the separators or `#`, and cannot start with `[`.
363
242
 
364
243
  - Sections and a DEFAULT section are supported. Section name are enclosed in `[ ]`.
365
244
  - Leading and trailing whitespace is trimmed off of the section name, and embedded whitespace is retained.
366
245
  EG: `[ hello my name is Fred ]` becomes section name `'hello my name is Fred'`.
367
- - Section names can contain most all characters, except `#` and `]`.
246
+ - Section names can contain most all characters, except `]`.
368
247
 
369
248
  - **Native int, float, bool, list, tuple, dict, str support** - Bool true/false is case insensitive. A str
370
- type is stored in the `cfg` dictionary if none of the other types can be resolved for a given param value.
249
+ type is stored in the `cfg` dictionary if none of the other types can be resolved for a given value_portion.
371
250
  Automatic typing avoids most explicit type casting clutter in the tool script. Be careful to error trap
372
251
  for type errors (eg, expecting a float but user input error resulted in a str). Also see the
373
- `getcfg (param, types=[])` parameter for basic type checking.
252
+ getcfg() `types=[]` parameter for basic type enforcement.
253
+
254
+ - **Quoted strings** - If a value_portion cannot be resolved to a Python native type then it is loaded as a str,
255
+ eg `My_name = George` loads George as a str. A value_portion may be forced to be loaded as a str by using
256
+ quotes, eg `Some_number_as_str = "2.54"` forces the value_portion to be loaded as a str rather than a float. Supported
257
+ quote types: `"..."`, `'...'`, (triple-double quotes), and `'''...'''`. `My_name = George`,
258
+ `My_name : "George"`, `My_name '''George'''`, etc., are identical when loaded.
259
+ Quoted strings may contain all valid characters, including '#' which normally starts a comment.
260
+
261
+ - **Multi-line values** - A param's value_portion may be specified over multiple lines for readability by placing
262
+ the `\` line continuation character as the last non-whitespace character on the line before any comment.
263
+ The parser strips comments and leading/trailing whitespace, then concatenates the multi-line value_portion segments
264
+ into a single line (single space separated) in the loaded config. Comments may be placed on each line.
265
+ NOTE: For a multi-line param that will be loaded as a str, avoid using quotes as results may be strange.
374
266
 
375
267
  - **Logging setup** - `loadconfig()` calls `cjnfuncs.core.setuplogging()`. The `logging` handle is available for
376
268
  import by other modules (`from cjnfuncs.core import logging`). By default, logging will go to the
@@ -421,12 +313,14 @@ the tool script to do any post-config-load operations.
421
313
  reload of the config file.
422
314
  - **Note** that if using threading then a thread should be paused while the config file
423
315
  is being reloaded with `flush_on_reload=True` or `force_flush_reload=True` since the params will disappear briefly.
316
+ Use the `prereload_callback` mechanism to manage any code dependencies before the cfg dictionary is purged.
424
317
  - Changes to imported files are not tracked for changes.
425
318
 
426
319
  - **Tolerating intermittent config file access** - When implementing a service loop, if `tolerate_missing=True`
427
320
  (default False) then loadconfig() will return `-1` if the config file cannot be accessed, informing the
428
- tool script of the problem for appropriate handling. If `tolerate_missing=False` then loadconfig() will raise
429
- a ConfigError if the config file cannot be accessed.
321
+ tool script of the problem for appropriate handling (typically logging the event then ignoring the problem for
322
+ the current iteration). If `tolerate_missing=False` then loadconfig() will raise a ConfigError if the config file
323
+ cannot be accessed.
430
324
  """
431
325
 
432
326
  global initial_logging_setup_done
@@ -434,8 +328,8 @@ a ConfigError if the config file cannot be accessed.
434
328
 
435
329
  if not initial_logging_setup_done:
436
330
  # Initial logging will go to the console if no call_logfile is specified (and call_logfile_wins) on the initial loadconfig call.
437
- console_lf = self.getcfg("ConsoleLogFormat", None)
438
- file_lf = self.getcfg("FileLogFormat", None)
331
+ console_lf = self.getcfg('ConsoleLogFormat', None)
332
+ file_lf = self.getcfg('FileLogFormat', None)
439
333
  setuplogging (call_logfile=call_logfile, call_logfile_wins=call_logfile_wins, ConsoleLogFormat=console_lf, FileLogFormat=file_lf)
440
334
  initial_logging_setup_done = True
441
335
 
@@ -495,22 +389,21 @@ a ConfigError if the config file cannot be accessed.
495
389
 
496
390
  # Operations only for finishing a top-level call
497
391
  if not isimport and not self.secondary_config:
498
- console_lf = self.getcfg("ConsoleLogFormat", None)
499
- file_lf = self.getcfg("FileLogFormat", None)
500
- setuplogging(config_logfile=self.getcfg("LogFile", None), call_logfile=call_logfile, call_logfile_wins=call_logfile_wins, ConsoleLogFormat=console_lf, FileLogFormat=file_lf)
392
+ console_lf = self.getcfg('ConsoleLogFormat', None)
393
+ file_lf = self.getcfg('FileLogFormat', None)
394
+ setuplogging(config_logfile=self.getcfg('LogFile', None), call_logfile=call_logfile, call_logfile_wins=call_logfile_wins, ConsoleLogFormat=console_lf, FileLogFormat=file_lf)
501
395
 
502
396
  if 'SMTP' in self.sections_list:
503
- if self.getcfg("DontEmail", False, section='SMTP'):
504
- logging.info ('DontEmail is set - Emails and Notifications will NOT be sent')
505
- elif self.getcfg("DontNotif", False, section='SMTP'):
506
- logging.info ('DontNotif is set - Notifications will NOT be sent')
397
+ if self.getcfg('DontEmail', False, section='SMTP'):
398
+ logging.info ("DontEmail is set - Emails and Notifications will NOT be sent")
399
+ elif self.getcfg('DontNotif', False, section='SMTP'):
400
+ logging.info ("DontNotif is set - Notifications will NOT be sent")
507
401
 
508
- config_loglevel = self.getcfg("LogLevel", None)
402
+ config_loglevel = self.getcfg('LogLevel', None)
509
403
  if config_loglevel is not None:
510
404
  try:
511
405
  config_loglevel = int(config_loglevel) # Handles force_str=True
512
406
  except:
513
- # if not isinstance(config_loglevel, int):
514
407
  raise ConfigError (f"Config file <LogLevel> must be integer value (found <{config_loglevel}>)") from None
515
408
  logging.info (f"Logging level set to config LogLevel <{config_loglevel}>")
516
409
  logging.getLogger().setLevel(config_loglevel)
@@ -566,57 +459,93 @@ flush_on_reload, force_flush_reload, and tolerate_missing.
566
459
  ### Behaviors and rules
567
460
  - See loadconfig() for config loading Behaviors and rules.
568
461
  """
462
+ continuation_line = False
463
+ split_line_re = re.compile(r'([^\s=:#]+)[\s=:]*(.*)') # Identify param - value (with possible comment)
464
+ xx = fr"""
465
+ ('''|\""") # Match opening triple quotes
466
+ (?:\\.|(?!\1).)*?\1 # Match content inside triple quotes until matching closing
467
+ | # OR
468
+ (["'])(?:\\.|(?!\2).)*?\2 # Match single or double quotes with matching pairs
469
+ | # OR
470
+ (\#) # Match unquoted # (group 3)
471
+ """
472
+ find_comment_re = re.compile(xx, re.VERBOSE) # Find unquoted '#'
473
+ section_name_re = re.compile(r'\[([^\].]*)\]') # Get section name
474
+
569
475
 
570
476
  for line in str_blob.split('\n'):
571
477
 
572
- # Is an import line
573
- if line.strip().lower().startswith("import"):
574
- line = line.split("#", maxsplit=1)[0].strip()
575
- target = mungePath(line.split(maxsplit=1)[1], self.config_dir)
576
- try:
577
- imported_config = config_item(target.full_path)
578
- imported_config.loadconfig(ldcfg_ll, isimport=True)
579
- for key in imported_config.cfg:
580
- if self.current_section_name == '':
581
- self.cfg[key] = imported_config.cfg[key]
582
- elif self.current_section_name == 'DEFAULT':
583
- self.defaults[key] = imported_config.cfg[key]
584
- else:
585
- self.cfg[self.current_section_name][key] = imported_config.cfg[key]
586
- except Exception as e:
478
+ if line.strip().startswith('['): # Section
479
+ section_name = None
480
+ out = section_name_re.match(line)
481
+ if out:
482
+ section_name = out.group(1).strip()
483
+ if section_name != '' and section_name not in self.sections_list and section_name != 'DEFAULT':
484
+ self.cfg[section_name] = {}
485
+ self.sections_list.append(section_name)
486
+ if section_name is None:
587
487
  logging.getLogger().setLevel(preexisting_loglevel)
588
- raise e
589
-
590
- # Is a param/value line or a [section] line
488
+ raise ConfigError (f"Malformed section line <{line}>")
489
+ else:
490
+ if isimport:
491
+ logging.getLogger().setLevel(preexisting_loglevel)
492
+ raise ConfigError ("Section within imported file is not supported.")
493
+ self.current_section_name = section_name
494
+ continue
495
+
496
+ if not continuation_line:
497
+ param_name = value_portion = ''
498
+ out = split_line_re.match(line.strip())
499
+ if out:
500
+ param_name = out.group(1)
501
+ value_portion = out.group(2)
591
502
  else:
592
- _line = line.split("#", maxsplit=1)[0].strip() # line without comment and leading/trailing whitespace
593
- if len(_line) > 0:
594
- if _line.startswith('['): # Section
595
- xx = self._check_section(_line)
596
- if xx is None:
597
- logging.getLogger().setLevel(preexisting_loglevel)
598
- raise ConfigError (f"Malformed section line <{line}>")
599
- else:
600
- if isimport:
601
- logging.getLogger().setLevel(preexisting_loglevel)
602
- raise ConfigError ("Section within imported file is not supported.")
603
- self.current_section_name = xx
604
-
605
- else: # param/value
606
- out = CFGLINE.match(_line)
607
- if out:
608
- param = out.group(1)
609
- rol = out.group(2) # rest of line (value portion)
610
-
611
- if rol == '': # param with no value stored as True
612
- value = True
503
+ value_portion += ' ' + line.strip()
504
+ continuation_line = False
505
+
506
+ if value_portion != '':
507
+ # Remove after first '#' outside of quotes
508
+ for match in find_comment_re.finditer(value_portion):
509
+ if match.group(3):
510
+ value_portion = value_portion[:match.start(3)].strip()
511
+ break
512
+
513
+ if value_portion.endswith('\\'): # Continuation line
514
+ value_portion = value_portion[:-1].strip()
515
+ continuation_line = True
516
+ continue
517
+
518
+ if param_name != '':
519
+ if param_name.lower().startswith('import'): # import line
520
+ target = mungePath(value_portion, self.config_dir)
521
+ try:
522
+ imported_config = config_item(target.full_path)
523
+ imported_config.loadconfig(ldcfg_ll, isimport=True)
524
+ for key in imported_config.cfg:
525
+ if self.current_section_name == '':
526
+ self.cfg[key] = imported_config.cfg[key]
527
+ elif self.current_section_name == 'DEFAULT':
528
+ self.defaults[key] = imported_config.cfg[key]
613
529
  else:
614
- value = self._parse_value(rol)
615
- self._add_key(param, value, self.current_section_name)
616
- logging.debug (f"Loaded {param} = <{value}> ({type(value)})")
617
- else:
618
- line = line.replace('\n','')
619
- logging.warning (f"loadconfig: Error on line <{line}>. Line skipped.")
530
+ self.cfg[self.current_section_name][key] = imported_config.cfg[key]
531
+ except Exception as e:
532
+ logging.getLogger().setLevel(preexisting_loglevel)
533
+ raise e
534
+ else: # param - value line
535
+ if value_portion.lower() == 'true':
536
+ value_portion = 'True'
537
+ if value_portion.lower() == 'false':
538
+ value_portion = 'False'
539
+ if value_portion == '':
540
+ value_portion = 'True'
541
+ if not self.force_str:
542
+ try:
543
+ value_portion = ast.literal_eval(value_portion)
544
+ except:
545
+ pass # default to str
546
+ self._add_key(param_name, value_portion, self.current_section_name)
547
+ logging.debug (f"Loaded {param_name} = <{value_portion}> ({type(value_portion)})")
548
+
620
549
 
621
550
 
622
551
  #=====================================================================================
@@ -685,8 +614,6 @@ Loaded content is added to and/or modifies any previously loaded content.
685
614
  self.sections_list.append(section_name)
686
615
  for key in param_dict:
687
616
  self.cfg[section_name][key] = param_dict[key]
688
- # except Exception as e:
689
- # raise ConfigError (f"Failed loading dictionary into cfg around key <{key}>")
690
617
  except Exception:
691
618
  raise ConfigError (f"Failed loading dictionary into cfg around key <{key}>")
692
619
 
@@ -723,8 +650,9 @@ This can lead to cleaner tool script code. Either access method may be used, al
723
650
  `param` (str)
724
651
  - String name of param to be fetched from cfg
725
652
 
726
- `fallback` (as-expected type, default None)
653
+ `fallback` (any, default effectively `None`, technically '_nofallback')
727
654
  - if provided, is returned if `param` does not exist in cfg
655
+ - No type enforcement - the fallback value need not be in the `types` list.
728
656
 
729
657
  `types` (single or list of as-expected types, default '[]' (any type accepted))
730
658
  - if provided, a ConfigError is raised if the param's value type is not in the list of expected types
@@ -758,7 +686,7 @@ This can lead to cleaner tool script code. Either access method may be used, al
758
686
  _value = self.defaults[param]
759
687
 
760
688
  if _value is None:
761
- if fallback != "_nofallback":
689
+ if fallback != '_nofallback':
762
690
  return fallback
763
691
  else:
764
692
  raise ConfigError (f"Param <[{section}] {param}> not in <{self.config_file}> and no default or fallback.")
@@ -804,16 +732,12 @@ all changes have been applied the final call to modify_configfile() must have `s
804
732
  cause the memory version to be written out to the config file. If the script code checks for
805
733
  modifications of the config file then the modified content will be reloaded into the cfg dictionary.
806
734
 
807
- NOTE: In some circumstances the OS-reported timestamp for the modified config file may be erratic.
808
- It may be necessary to add a time.sleep(0.5) delay between saving the modified config and the loadconfig()
809
- reload call to avoid multiple config reloads.
810
-
811
735
 
812
736
  ### Parameters
813
737
  `param` (str, default '')
814
738
  - The param name, if modifying an existing param or adding a new param
815
739
 
816
- `value` (as-expected type, default '')
740
+ `value` (any, default '')
817
741
  - The new value to be applied to an existing param, or an added param
818
742
  - Any comment text (after a '#') in the new value will be prepended to any existing comment text
819
743
 
@@ -833,19 +757,31 @@ reload call to avoid multiple config reloads.
833
757
  ### Returns
834
758
  - No return value
835
759
  - Warning messages are logged for attempting to modify or remove a non-existing param.
760
+
761
+
762
+ ### Behaviors and rules
763
+ - **How modify_config works with multi-line params -** If a multi-line param is modified, the new value is
764
+ written out on a single line, and the continuation lines for the original definition remain in place.
765
+ This effectively turns the continuation lines into a new param definition, which is usually benign. Check
766
+ for param name conflicts.
767
+ - NOTE: In some circumstances the OS-reported timestamp for the modified config file may be erratic.
768
+ It may be necessary to add a `time.sleep(0.5)` delay between saving the modified config and the loadconfig()
769
+ reload call to avoid multiple config reloads.
836
770
  """
837
771
 
772
+ line_format_re = re.compile(r'(\s*)([^\s=:]+)([\s=:]+)([^#]+)(.*)')
773
+
838
774
  if self.config_file is None:
839
775
  raise ConfigError ("Config file is None. Cannot modify config not loaded from a file.")
840
776
 
841
- if self.config_content == "":
777
+ if self.config_content == '':
842
778
  self.config_content = self.config_full_path.read_text()
843
779
  found_param = False
844
- updated_content = ""
780
+ updated_content = ''
845
781
  value = str(value)
846
782
 
847
- for line in self.config_content.split("\n"):
848
- out = CFGLINE2.match(line)
783
+ for line in self.config_content.split('\n'):
784
+ out = line_format_re.match(line)
849
785
  if out:
850
786
  # print (f"1: <{out.group(1)}>") # Any leading whitespace
851
787
  # print (f"2: <{out.group(2)}>") # param
@@ -854,7 +790,7 @@ reload call to avoid multiple config reloads.
854
790
  # print (f"5: <{out.group(5)}>") # comment
855
791
 
856
792
  if out.group(2) != param:
857
- updated_content += line + "\n"
793
+ updated_content += line + '\n'
858
794
  else:
859
795
  found_param = True
860
796
  if remove == True:
@@ -867,14 +803,14 @@ reload call to avoid multiple config reloads.
867
803
  len_new_whitespace = 1
868
804
  if len_current_whitespace == 0:
869
805
  len_new_whitespace = 0
870
- updated_content += out.group(1) + out.group(2) + out.group(3) + value + ' '*len_new_whitespace + out.group(5) + "\n"
806
+ updated_content += out.group(1) + out.group(2) + out.group(3) + value + ' '*len_new_whitespace + out.group(5) + '\n'
871
807
  else:
872
- updated_content += line + "\n"
808
+ updated_content += line + '\n'
873
809
 
874
810
  if found_param == False:
875
811
  if add_if_not_existing == True:
876
812
  updated_content += f"{param} {value}\n"
877
- elif param=="" and value=="" and save==True: # Save-only call
813
+ elif param=='' and value=='' and save==True: # Save-only call
878
814
  pass
879
815
  else:
880
816
  logging.warning (f"Modification of param <{param}> failed - not found in config file. Modification skipped.")
@@ -882,8 +818,8 @@ reload call to avoid multiple config reloads.
882
818
  self.config_content = updated_content[:-1] # Avoid adding extra \n at end of file
883
819
 
884
820
  if save:
885
- self.config_full_path.write_text(self.config_content) # + "\n")
886
- self.config_content = ""
821
+ self.config_full_path.write_text(self.config_content)
822
+ self.config_content = ''
887
823
 
888
824
 
889
825
  #=====================================================================================
@@ -918,12 +854,15 @@ reload call to avoid multiple config reloads.
918
854
  cfg_list = ''
919
855
  for key in self.cfg:
920
856
  if key not in self.sections_list:
921
- cfg_list += f"{key:20} = {self.cfg[key]}\n"
922
- cfg_list += f"\n[DEFAULT]\n"
857
+ if type(self.cfg[key]) is str and '#' in self.cfg[key]:
858
+ cfg_list += f"{key:20} = '''{self.cfg[key]}'''\n"
859
+ else:
860
+ cfg_list += f"{key:20} = {self.cfg[key]}\n"
861
+ cfg_list += '\n[DEFAULT]\n'
923
862
  for key in self.defaults:
924
863
  cfg_list += f"{key:20} = {self.defaults[key]}\n"
925
864
  for section in self.sections_list:
926
- cfg_list += f"\n[{section}]\n"
865
+ cfg_list += f'\n[{section}]\n'
927
866
  for key in self.cfg[section]:
928
867
  cfg_list += f"{key:20} = {self.cfg[section][key]}\n"
929
868
 
@@ -937,4 +876,119 @@ reload call to avoid multiple config reloads.
937
876
  logging.debug(f"Failed try {ntry} to write config {self.config_file} to file {outfile}\n {e}")
938
877
 
939
878
  raise ConfigError (f"Failed to write config {self.config_file} to file {outfile}\n {_e}")
940
-
879
+
880
+
881
+ #=====================================================================================
882
+ #=====================================================================================
883
+ # s e c t i o n s
884
+ #=====================================================================================
885
+ #=====================================================================================
886
+
887
+ def sections(self):
888
+ """
889
+ ## sections () - Return a list of sections in the cfg dictionary
890
+
891
+ ***config_item() class member function***
892
+
893
+ For compatibility with the standard library configparser. Also available via `<config>.sections_list`.
894
+
895
+ Example:
896
+ ```
897
+ code:
898
+ print (my_config.sections())
899
+
900
+ output:
901
+ ['Bad params', 'SMTP']
902
+ ```
903
+ """
904
+
905
+ return self.sections_list
906
+
907
+
908
+ #=====================================================================================
909
+ #=====================================================================================
910
+ # c l e a r
911
+ #=====================================================================================
912
+ #=====================================================================================
913
+
914
+ def clear(self, section=''):
915
+ """
916
+ ## clear (section='') - Purge a portion of the cfg dictionary
917
+
918
+ ***config_item() class member function***
919
+
920
+ ### Parameters
921
+ `section` (str, default '')
922
+ - `section = ''` clears the entire cfg dictionary, including all sections and DEFAULT
923
+ - `section = '<section_name>'` clears just that section
924
+ - `section = 'DEFAULT'` clears just the DEFAULT section
925
+
926
+
927
+ ### Returns
928
+ - A ConfigError is raised if attempting to remove a non-existing section
929
+ """
930
+
931
+ if section == '':
932
+ self.cfg.clear()
933
+ self.sections_list = []
934
+ self.defaults.clear()
935
+ elif section in self.sections_list:
936
+ self.cfg.pop(section, None)
937
+ self.sections_list.remove(section)
938
+ elif section == 'DEFAULT':
939
+ self.defaults.clear()
940
+ else:
941
+ raise ConfigError (f"Failed attempt to remove non-existing section <{section}> from config")
942
+
943
+
944
+ #=====================================================================================
945
+ #=====================================================================================
946
+ # _ _ r e p r _ _
947
+ #=====================================================================================
948
+ #=====================================================================================
949
+
950
+ def __repr__(self):
951
+ stats = ""
952
+ stats += f"\nStats for config file <{self.config_file}>:\n"
953
+ stats += f".config_file : {self.config_file}\n"
954
+ stats += f".config_dir : {self.config_dir}\n"
955
+ stats += f".config_full_path : {self.config_full_path}\n"
956
+ stats += f".config_timestamp : {self.config_timestamp}\n"
957
+ stats += f".sections_list : {self.sections_list}\n"
958
+ stats += f".force_str : {self.force_str}\n"
959
+ stats += f".secondary_config : {self.secondary_config}\n"
960
+ stats += f"core.tool.log_dir_base : {core.tool.log_dir_base}\n"
961
+ return stats
962
+
963
+
964
+ #=====================================================================================
965
+ #=====================================================================================
966
+ # d u m p
967
+ #=====================================================================================
968
+ #=====================================================================================
969
+
970
+ def dump(self):
971
+ """
972
+ ## dump () - Return the formatted content of the cfg dictionary
973
+
974
+ ***config_item() class member function***
975
+
976
+
977
+ ### Returns
978
+ - str type pretty formatted content of the cfg dictionary, along with any sections and defaults
979
+ """
980
+
981
+ cfg_list = "***** Section [] *****\n"
982
+ for key in self.cfg:
983
+ if key not in self.sections_list:
984
+ cfg_list += f"{key:>20} = {self.cfg[key]} {type(self.cfg[key])}\n"
985
+ for section in self.sections_list:
986
+ cfg_list += f"***** Section [{section}] *****\n"
987
+ for key in self.cfg[section]:
988
+ cfg_list += f"{key:>20} = {self.cfg[section][key]} {type(self.cfg[section][key])}\n"
989
+ cfg_list += f"***** Section [DEFAULT] *****\n"
990
+ for key in self.defaults:
991
+ cfg_list += f"{key:>20} = {self.defaults[key]} {type(self.defaults[key])}\n"
992
+ return cfg_list[:-1] # drop final '\n'
993
+
994
+
@@ -208,7 +208,7 @@ the log file declared in the config file:
208
208
 
209
209
 
210
210
  ### Parameters
211
- `call_logfile` (str, default None)
211
+ `call_logfile` (Path or str, default None)
212
212
  - Potential log file passed typically from the tool script. Selected by `call_logfile_wins = True`.
213
213
  call_logfile may be an absolute path or relative to the `core.tool.log_dir_base` directory.
214
214
  - `None` specifies the console.
@@ -46,6 +46,8 @@ process completes its work, and then acquire the I2C bus lock so that other proc
46
46
  - Resource locks are on the honor system. Any process can unget a lock, but should not if it didn't get the lock.
47
47
  - This lock mechanism is just as effective across threads within a process.
48
48
  - As many different/independent locks as needed may be created.
49
+ - The first time a lock is created (on the current computer since reboot) the lock info string (accessible via `get_lock_info()`)
50
+ is set to '', else it retains the value set by the most recent get_lock() call.
49
51
  - It is recommended (in order to avoid a minor memory leak) to `close()` the lock in the tool script cleanup code.
50
52
  Calling `close()` sets the `closed` attribute to True so that any following code can detect and re-instantiate the
51
53
  lock if needed.
@@ -90,10 +92,16 @@ checked and re-instantiate if needed.
90
92
  self.I_have_the_lock = False
91
93
  self.lock = posix_ipc.Semaphore(self.lockname, flags=posix_ipc.O_CREAT, mode=0o0600, initial_value=1)
92
94
 
93
- memory = posix_ipc.SharedMemory(self.lockname, flags=posix_ipc.O_CREAT, mode=0o0600, size=4096)
95
+ preexisting = False
96
+ try:
97
+ memory = posix_ipc.SharedMemory(self.lockname, flags=0)
98
+ preexisting = True
99
+ except posix_ipc.ExistentialError:
100
+ memory = posix_ipc.SharedMemory(self.lockname, flags=posix_ipc.O_CREAT, mode=0o0600, size=4096)
101
+
94
102
  self.mapfile = mmap.mmap(memory.fd, memory.size)
95
103
  os.close(memory.fd)
96
- if not self.is_locked():
104
+ if not preexisting:
97
105
  self._set_lock_info('')
98
106
 
99
107
 
@@ -1,6 +1,6 @@
1
- Metadata-Version: 2.1
1
+ Metadata-Version: 2.2
2
2
  Name: cjnfuncs
3
- Version: 2.4
3
+ Version: 2.5
4
4
  Summary: A collection of core functions for tool script writing
5
5
  Author-email: Chris Nelson <github@cjnaz.com>
6
6
  License: MIT License
@@ -75,6 +75,8 @@ Project repo: https://github.com/cjnaz/cjnfuncs
75
75
  <br/>
76
76
 
77
77
  ## Revision history
78
+ - 2.5 250206 - Added multi-line and quoted string support to configman
79
+ - 2.4.1 241118 - resource_lock only init lock_info if not existing
78
80
  - 2.4 241105 - Twilio support in snd_notif, resource_lock trace/debug features, check_path_exists exception fix
79
81
  - 2.3 240821 - Added mungePath ./ support.
80
82
  Resolved check_path_exists() memory leak.
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes