bw2 / ConfigArgParse

A drop-in replacement for argparse that allows options to also be set via config files and/or environment variables.
MIT License
719 stars 121 forks source link

Add option to ignore config file paths #254

Open mathisloevenich opened 2 years ago

mathisloevenich commented 2 years ago

It would be nice to have an option like

--ignore-config

to ignore even the default config paths

mathisloevenich commented 2 years ago

An easy work-around to this is:

class MyArgumentParser(ArgumentParser):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

    def set_default_config_paths(self, config_paths):
        self._default_config_files = config_paths
parser = MyArgumentParser()
parser.add_argument("--ignore-config", action="store_true")
args = parser.parse_args()
if not args.ignore_config:
    parser.set_default_config_paths(["/etc/conf/app_config.ini"])
args = parser.parse_args()

In this case we add the config paths after parsing the arguments once. Not really beautiful, but working solution.

mathisloevenich commented 2 years ago

But I would recomment to add a flag to the add_argument method.

mathisloevenich commented 2 years ago

Be aware that this messes up the help description. Rather use:

args=sys.argv[1:]
parser = MyArgumentParser()
parser.add_argument("--ignore-config", action="store_true")

if "-h" in args or "--help" in args:
    parser.set_default_config_paths(["/etc/conf/app_config.ini"])
    parser.parse_args(["-h"])
    # exit

args = parser.parse_args()
if not args.ignore_config:
    parser.set_default_config_paths(["/etc/conf/app_config.ini"])
args = parser.parse_args()
mathisloevenich commented 2 years ago

In my case this is working for me:

class CLIArgumentParser(ArgumentParser):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

    def set_default_config_paths(self, config_paths):
        self._default_config_files = config_paths

    def get_arguments(self, args):
        # add config paths if help wanted
        if "-h" in args or "--help" in args:
            self.set_default_config_paths(CONFIG_PATHS)
            self.parse_args(["-h"])
            # exit

        # else check if --ignore-config is set
        prio_args = self.parse_args(args)
        if not prio_args.ignore_config:
            # if not set add config paths
            self.set_default_config_paths(CONFIG_PATHS)

        return self.parse_args(args)

where CONFIG_PATHS = [first_path, second_path, ...]