def _handle_kwargs(self, kwargs): """ **kwargs been input """ if ID_CONFIG in kwargs: if len(kwargs) > 2 or (len(kwargs) == 2 and ID_SECTION not in kwargs): raise ArgumentError( "Only '{:s}' and '{:s}'".format(ID_CONFIG, ID_SECTION) + " arguments are allowed, when using a config file.") options = self._read_config(kwargs[ID_CONFIG], kwargs.get(ID_SECTION, None)) options = self.dictparse.parse_config_items(options) elif ID_DICT in kwargs: if len(kwargs) > 1: raise ArgumentError("Only one argument allowed when using a dictionary") options = self.dictparse.parse_arguments(kwargs[ID_DICT]) elif ID_JSON in kwargs: if len(kwargs) > 2 or (len(kwargs) == 2 and ID_SECTION not in kwargs): raise ArgumentError( "Only '{:s}' and '{:s}'".format(ID_JSON, ID_SECTION) + " arguments are allowed, when using a json file.") with open(kwargs[ID_JSON], 'r') as json_file: json_dict = json.load(json_file) if ID_SECTION in kwargs: json_dict = json_dict[kwargs[ID_SECTION]] options = self.dictparse.parse_arguments(json_dict) else: options = self.dictparse.parse_arguments(kwargs) return options # options might include known and unknown options
def __call__(self, func): """ Builds wrapper around the function 'func' (called on decoration) Whenever the decorated function is called, actually this wrapper is called. The Number of arguments is checked for compliance with instance- and class- methods, Meaning: if there is one more argument as there should be, we pass it on as it is (should be) either ``self`` or ``cls``. One could check that there are no varargs and keywords, but let's assume the user is doing the right things. """ nargs = len(getfullargspec(func).args) if self.strict: if nargs == 1: @wraps(func) def wrapper(*args, **kwargs): return func(self.parse(*args, **kwargs)) elif nargs == 2: @wraps(func) def wrapper(other, *args, **kwargs): return func(other, self.parse(*args, **kwargs)) else: ArgumentError( "In strict mode, only one option-structure will be passed." " The entrypoint needs to have the following structure: " " ([self/cls,] options)." " Found: {:s}".format(getfullargspec(func).args)) else: if nargs == 2: @wraps(func) def wrapper(*args, **kwargs): options, unknown_options = self.parse(*args, **kwargs) return func(options, unknown_options) elif nargs == 3: @wraps(func) def wrapper(other, *args, **kwargs): options, unknown_options = self.parse(*args, **kwargs) return func(other, options, unknown_options) else: ArgumentError( "Two option-structures will be passed." " The entrypoint needs to have the following structure: " " ([self/cls,] options, unknown_options)." " Found: {:s}".format(getfullargspec(func).args)) return wrapper
def parse(self, *args, **kwargs): """ Parse whatever input parameter come. This is the heart of EntryPoint and will recognize the input and parse it accordingly. Allowed inputs are: - Dictionary with arguments as key-values - Key-Value arguments - Path to a one-section config file - Commandline Arguments - Commandline Arguments in string-form (as list) - Special Key-Value arguments are: entry_dict: Value is a dict of arguments entry_cfg: Path to config file entry_json: Path to json file section: Section to use in config file, or subdirectory to use in json file. Only works with the key-value version of config file. If not given only one-section config files are allowed. """ if len(args) > 0 and len(kwargs) > 0: raise ArgumentError( "Cannot combine positional parameter with keyword parameter.") if len(args) > 1: raise ArgumentError( "Only one positional argument allowed (dict or config file).") if args and args[0] is not None: # LOG.info("Entry input: {:s}".format(args[0])) # activate for debugging options = self._handle_arg(args[0]) elif len(kwargs) > 0: # LOG.info("Entry input: {:s}".format(kwargs)) # activate for debugging options = self._handle_kwargs(kwargs) else: # LOG.info("Entry input: {:s}".format(" ".join(sys.argv)) # activate for debugging options = self._handle_commandline() return options # options might include known and unknown options
def _read_config(self, cfgfile_path, section=None): """ Get content from config file""" cfgparse = self.configparse with open(cfgfile_path) as config_file: cfgparse.readfp(config_file) sections = cfgparse.sections() if not section and len(sections) == 1: section = sections[0] elif not section: raise ArgumentError("'{:s}' contains multiple sections. Please specify one!") return cfgparse.items(section)
def _handle_arg(self, arg): """ *args has been input """ if isinstance(arg, basestring): # assume config file options = self.dictparse.parse_config_items(self._read_config(arg)) elif isinstance(arg, dict): # dictionary options = self.dictparse.parse_arguments(arg) elif isinstance(arg, list): # list of commandline parameter options = self._handle_commandline(arg) else: raise ArgumentError("Only dictionary or configfiles " "are allowed as positional arguments") return options # options might include known and unknown options
def _handle_commandline(self, args=None): """ No input to function """ try: # check for config file first with silence(): options = self.configarg.parse_args(args) except SystemExit: # parse regular options options, unknown_opts = self.argparse.parse_known_args(args) options = DotDict(vars(options)) if self.strict: if unknown_opts: raise ArgumentError("Unknown options: {:s}".format(unknown_opts)) return options else: if unknown_opts: LOG.debug("Unknown options: {:s}".format(unknown_opts)) return options, unknown_opts else: # parse config file return self.dictparse.parse_config_items(self._read_config(vars(options)[ID_CONFIG]))
def main(opt, accel_opt): if len(opt.corrections) or len(opt.labels): if len(opt.corrections) != len(opt.labels): raise ArgumentError( "Length of labels and corrections need to be equal.") accel_cls = manager.get_accel_class(accel_opt) if "lhc" not in accel_cls.NAME: raise AcceleratorDefinitionError("Only implemented for LHC") accel_inst = accel_cls(model_dir=opt.model_dir) if opt.optics_file is not None: accel_inst.optics_file = opt.optics_file locations = _get_locations_of_interest(accel_inst) results = {} results["main"] = _get_result(accel_inst, locations) for correction, label in zip(opt.corrections, opt.labels): results[label] = _get_result(accel_inst, locations, correction) _write_results(opt.output_dir, results)