From 8438f95e687a5563ad454b7364bb54bd07122083 Mon Sep 17 00:00:00 2001 From: Benjamin Renard Date: Fri, 19 Nov 2021 16:16:46 +0100 Subject: [PATCH] Config: Add config_file_env_variable parameter The new config_file_env_variable parameter allow to specify environment variable name that will be used to determine configuration file path if it's not explicitly provided using -c/--config parameter. --- mylib/config.py | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) diff --git a/mylib/config.py b/mylib/config.py index 54d4060..00eabda 100644 --- a/mylib/config.py +++ b/mylib/config.py @@ -412,7 +412,8 @@ class RawWrappedTextHelpFormatter(argparse.RawDescriptionHelpFormatter): class Config: """ Configuration helper """ - def __init__(self, appname, shortname=None, version=None, encoding=None): + def __init__(self, appname, shortname=None, version=None, encoding=None, + config_file_env_variable=None): self.appname = appname self.shortname = shortname self.version = version if version else '0.0' @@ -424,6 +425,7 @@ class Config: self._loaded_callbacks = [] self._loaded_callbacks_executed = [] self._filepath = None + self.config_file_env_variable = config_file_env_variable def add_section(self, name, loaded_callback=None, **kwargs): """ @@ -567,12 +569,14 @@ class Config: formatter_class=RawWrappedTextHelpFormatter, **kwargs) + config_file_help = 'Configuration file to use (default: %s)' % self.config_filepath + if self.config_file_env_variable: + config_file_help += '\n\nYou also could set %s environment variable to specify your configuration file path.' % self.config_file_env_variable self.options_parser.add_argument( '-c', '--config', default=self.config_filepath, - help='Configuration file to use (default: %s)' % - self.config_filepath + help=config_file_help ) self.options_parser.add_argument( @@ -684,6 +688,8 @@ class Config: """ Retrieve configuration file path """ if self._filepath: return self._filepath + if self.config_file_env_variable and os.environ.get(self.config_file_env_variable): + return os.environ.get(self.config_file_env_variable) return os.path.join( self.config_dir, ("%s.ini" % self.shortname) if self.shortname