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 _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(
                    f"Only '{ID_CONFIG:s}' and '{ID_SECTION:s}'" +
                    " 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(
                    f"Only '{ID_JSON:s}' and '{ID_SECTION:s}'" +
                    " 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 _handle_arg(self, arg):
     """ *args has been input """
     if isinstance(arg, str):
         # 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
示例#4
0
    def _read_config(self, cfgfile_path, section=None):
        """Get content from config file."""
        # create new config parser, as it keeps defaults between files
        cfgparse = self._create_config_parser()

        with open(cfgfile_path) as config_file:
            cfgparse.read_file(config_file)

        sections = cfgparse.sections()
        if not section:
            if len(sections) == 0:
                section = "DEFAULT"  # name does not matter, takes defaults, but None is not allowed
            elif len(sections) == 1:
                section = sections[0]  # our convention
            elif len(sections) > 1:
                raise ArgumentError(
                    f"'{cfgfile_path:s}' contains multiple sections. " +
                    " Please specify one!")

        items = cfgparse.items(section)
        return items
 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(f"Unknown options: {unknown_opts}")
             return options
         else:
             if unknown_opts:
                 LOG.debug(f"Unknown options: {unknown_opts}")
             return options, unknown_opts
     else:
         # parse config file
         return self.dictparse.parse_config_items(
             self._read_config(vars(options)[ID_CONFIG]))