12345678910111213141516171819202122232425262728293031323334353637383940414243 |
- import argparse
- import configparser
-
- from .errors import ConfigError
-
- # Config file section
- CONFIG_SECTION = 'pyws_clock'
- # Maps config key name to argparse arg name and type
- CONFIG_ARGS = {
- 'port': ('port', int),
- 'listen': ('listen_address', str),
- 'session_directory': ('session_dir', str),
- 'loglevel': ('verbose', int),
- 'logfile': ('logfile', str),
- }
-
- def parse_config(filename:str, args:argparse.Namespace):
- """ Updates args parsed by argparse using a configuration file
- @param filename : configuration file name
- @param args : Namespace returned by ArgumentParser.parse_args()
- @return updated Namespace
- @note args is modified by reference
- """
-
- config = configparser.ConfigParser()
- config.read(filename)
-
- if CONFIG_SECTION not in config:
- err = 'There is no section named %r in %r' % (CONFIG_SECTION, filename)
- raise ConfigError(err)
-
- err_key = []
- for key in config[CONFIG_SECTION]:
- if key not in CONFIG_ARGS:
- err_key.append(key)
- continue
- argname, argtype = CONFIG_ARGS[key]
- setattr(args, argname, argtype(config[CONFIG_SECTION][key]))
- if len(err_key) > 0:
- err = 'Invalid configuration key in %r : %r' % (filename,
- ','.join(err_key))
- raise ConfigError(err)
- return args
|