Skip to content

Instantly share code, notes, and snippets.

@jacquesfize
Created January 17, 2020 14:00
Show Gist options
  • Save jacquesfize/7fbfd68c38725b9948b8730d85342748 to your computer and use it in GitHub Desktop.
Save jacquesfize/7fbfd68c38725b9948b8730d85342748 to your computer and use it in GitHub Desktop.
Initialize ArgParse with a Json config file
import argparse
import os
import json
class ArgParseConfigurationReader(object):
"""
Example of config JSON :
{
"description": "Program",
"args": [
{ "short": "geoname_input", "help": "Filepath of the Geonames file you want to use." },
{ "short": "-v", "long": "--verbose", "action": "store_true" },
{ "short": "-n", "long": "--ngram-size", "type": "int", "default": 2 },
{ "short": "-t", "long": "--tolerance-value", "type": "float", "default": 0.002 },
{ "short": "-e", "long": "--epochs", "type": "int", "default": 100 },
{ "short": "-m", "long": "--model", "choices": ["CNN", "LSTM"], "default": "CNN" }
]
}
"""
def __init__(self,configuration_file):
if not os.path.exists(configuration_file):
raise FileNotFoundError("'{0} file could not be found ! '".format(configuration_file))
self.configuration = json.load(open(configuration_file))
self.__argparser_desc = ("" if not "description" in self.configuration else self.configuration["description"])
self.parser = argparse.ArgumentParser(description=self.__argparser_desc)
self.parse_conf()
def parse_conf(self):
if not "args" in self.configuration:
raise argparse.ArgumentError("","No args given in the configuration file")
for dict_args in self.configuration["args"]:
if not isinstance(dict_args,dict):
raise ValueError("Args must be dictionnary")
short_command = dict_args.get("short",None)
long_command = dict_args.get("long",None)
if not short_command and not long_command:
raise ValueError("No command name was given !")
add_func_dict_= {}
if "help" in dict_args:
add_func_dict_["help"]= dict_args["help"]
if "default" in dict_args:
add_func_dict_["default"]= dict_args["default"]
if "action" in dict_args:
add_func_dict_["action"]= dict_args["action"]
if "type" in dict_args:
add_func_dict_["type"]= eval(dict_args["type"])
if "choices" in dict_args:
add_func_dict_["choices"]= dict_args["choices"]
if not (short_command and long_command):
command = (short_command if not long_command else long_command)
self.parser.add_argument(command,**add_func_dict_)
elif long_command and short_command:
self.parser.add_argument(short_command,long_command,**add_func_dict_)
def parse_args(self,input_=None):
if not input_:
return self.parser.parse_args()
return self.parser.parse_args(input_)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment