Open mathisloevenich opened 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.
But I would recomment to add a flag to the add_argument
method.
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()
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, ...]
It would be nice to have an option like
--ignore-config
to ignore even the default config paths