From dbc31df823ca1e59563c97e1c16a1f1d18a828fd Mon Sep 17 00:00:00 2001 From: tengel Date: Wed, 20 Mar 2024 11:28:46 -0500 Subject: [PATCH] adding configcli --- python/configcli.py | 64 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100755 python/configcli.py diff --git a/python/configcli.py b/python/configcli.py new file mode 100755 index 0000000..5c0485b --- /dev/null +++ b/python/configcli.py @@ -0,0 +1,64 @@ +#!/usr/bin/env python3 +""" +Leverage the python ConfigParser() class for use as a commandline INI +file reader, can be used from bash to leverage all the safety in place. + +See: https://docs.python.org/2/library/configparser.html + +SPDX-License-Identifier: MIT +""" + +import argparse +import configparser +import signal + +__version__ = "0.0.1" + + +def read_ini(cfgfile, section, key): + # because we're simply printing to stdout, it really doesn't + # matter if the file is missing, the section, the key or the + # value - just try and get whatever is in there and print it + # out in a very bash-esque way. Just avoid all exceptions. + try: + config = configparser.ConfigParser() + config.read(cfgfile) + if config.has_option(section, key): + return config.get(section, key) + except: + pass + + # any error is just an empty string return + return "" + + +def parse_args(): + """Argument parsing routine""" + parser = argparse.ArgumentParser(description="ConfigCli") + parser.add_argument( + "--version", action="version", version=__version__, help="Display the version" + ) + parser.add_argument( + "-f", "--file", required=True, dest="cfgfile", help="Config file to read" + ) + parser.add_argument( + "-s", "--section", required=True, dest="section", help="Section to read" + ) + parser.add_argument("-k", "--key", required=True, dest="key", help="Key to read") + return parser.parse_args() + + +def sigbye_handler(signal, frame): + """Exit function triggered by caught signals""" + sys.exit(0) + + +if __name__ == "__main__": + """Main entry point for ConfigCli""" + # register a clean shutdown for the usual signals + signal.signal(signal.SIGINT, sigbye_handler) + signal.signal(signal.SIGQUIT, sigbye_handler) + signal.signal(signal.SIGTERM, sigbye_handler) + + args = parse_args() + print(read_ini(args.cfgfile, args.section, args.key))