当前位置: 首页>>代码示例>>Python>>正文


Python yaml.YAMLError方法代码示例

本文整理汇总了Python中yaml.YAMLError方法的典型用法代码示例。如果您正苦于以下问题:Python yaml.YAMLError方法的具体用法?Python yaml.YAMLError怎么用?Python yaml.YAMLError使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在yaml的用法示例。


在下文中一共展示了yaml.YAMLError方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: get_plugin_config

# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import YAMLError [as 别名]
def get_plugin_config(config_uri):
    """
    Downloads/opens configuration yaml file, returns
    dict of Galaxy plugins
    """
    # Try to open the URI as a URL or fall back to opening local file
    try:
        config_uri_parsed = urlparse(config_uri)
        if config_uri_parsed.scheme in ['https', 'http']:
            url = urlopen(config_uri)
            yaml_data = url.read()
        else:
            with open(config_uri, 'r') as file_data:
                yaml_data = file_data.read()
    except URLError as e:
        print(e)

    # Parse the YAML configuration
    try:
        plugin_data = yaml.safe_load(yaml_data)

        return plugin_data['plugins']
    except yaml.YAMLError as e:
        print(e) 
开发者ID:Slashbunny,项目名称:gog-galaxy-plugin-downloader,代码行数:26,代码来源:download.py

示例2: load_yaml_file

# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import YAMLError [as 别名]
def load_yaml_file(filename, label='config file', loader=yaml.Loader):
    """Load a yaml config file.
    """
    try:
        with open(filename, "r") as file:
            res = yaml.load(file.read(), Loader=loader) or {}
            if not isinstance(res, dict):
                msg = f"Please ensure that {label} consists of key value pairs."
                raise VergeMLError(f"Invalid {label}: {filename}", msg)
            return res
    except yaml.YAMLError as err:
        if hasattr(err, 'problem_mark'):
            mark = getattr(err, 'problem_mark')
            problem = getattr(err, 'problem')
            message = f"Could not read {label} {filename}:"
            message += "\n" + display_err_in_file(filename, mark.line, mark.column, problem)
        elif hasattr(err, 'problem'):
            problem = getattr(err, 'problem')
            message = f"Could not read {label} {filename}: {problem}"
        else:
            message = f"Could not read {label} {filename}: YAML Error"

        suggestion = f"There is a syntax error in your {label} - please fix it and try again."

        raise VergeMLError(message, suggestion)

    except OSError as err:
        msg = "Please ensure the file exists and you have the required access privileges."
        raise VergeMLError(f"Could not open {label} {filename}: {err.strerror}", msg) 
开发者ID:mme,项目名称:vergeml,代码行数:31,代码来源:config.py

示例3: _parse_package_list

# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import YAMLError [as 别名]
def _parse_package_list(self, data):
        """Parse data expecting a list of packages to install.

        Expect data to be a bytearray reprsenting a JSON or YAML
        document.

        :param data: A bytearray of data to parse
        """
        try:
            data_string = data.decode('utf-8')
            parsed_data = yaml.safe_load(data_string)

            if isinstance(parsed_data, dict):
                self.package_list = self._extract_package_list(parsed_data)
            else:
                raise errors.InvalidPackageListFormat(
                    "Package data should have a top-level mapping/object.")
        except yaml.YAMLError as ex:
            raise errors.InvalidPackageListFormat(
                "Invalid YAML in package list: %s" % str(ex)) 
开发者ID:airshipit,项目名称:drydock,代码行数:22,代码来源:bootaction.py

示例4: extract_yaml

# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import YAMLError [as 别名]
def extract_yaml(yaml_files):
    """
    Take a list of yaml_files and load them to return back
    to the testing program
    """
    loaded_yaml = []
    for yaml_file in yaml_files:
        try:
            with io.open(yaml_file, encoding='utf-8') as fd:
                loaded_yaml.append(yaml.safe_load(fd))
        except IOError as e:
            print('Error reading file', yaml_file)
            raise e
        except yaml.YAMLError as e:
            print('Error parsing file', yaml_file)
            raise e
        except Exception as e:
            print('General error')
            raise e
    return loaded_yaml 
开发者ID:CRS-support,项目名称:ftw,代码行数:22,代码来源:util.py

示例5: _parse_penalty_rules_yaml

# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import YAMLError [as 别名]
def _parse_penalty_rules_yaml(penalty_rules):
  try:
    penalty_rules = yaml.safe_load(penalty_rules)
  except yaml.YAMLError:
    raise error.ValidationError('penalty_rules', 'parse error')
  if not isinstance(penalty_rules, dict):
    raise error.ValidationError('penalty_rules', 'invalid format')
  new_rules = collections.OrderedDict()
  try:
    for time, coefficient in sorted(penalty_rules.items(), key=lambda x: float(x[0])):
      time_val = str(int(float(time) * 60 * 60))
      coefficient_val = float(coefficient)
      new_rules[time_val] = coefficient_val
  except ValueError:
    raise error.ValidationError('penalty_rules', 'value error')
  return new_rules 
开发者ID:vijos,项目名称:vj4,代码行数:18,代码来源:homework.py

示例6: extract_yaml

# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import YAMLError [as 别名]
def extract_yaml(yaml_files):
    """
    Take a list of yaml_files and load them to return back
    to the testing program
    """
    loaded_yaml = []
    for yaml_file in yaml_files:
        try:
            with open(yaml_file, 'r') as fd:
                loaded_yaml.append(yaml.safe_load(fd))
        except IOError as e:
            print('Error reading file', yaml_file)
            raise e
        except yaml.YAMLError as e:
            print('Error parsing file', yaml_file)
            raise e
        except Exception as e:
            print('General error')
            raise e
    return loaded_yaml 
开发者ID:fastly,项目名称:ftw,代码行数:22,代码来源:util.py

示例7: load

# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import YAMLError [as 别名]
def load(self, filename):
        try:
            stream = file(filename, 'r')
            res_config = yaml.safe_load(stream)
        except yaml.YAMLError as err:
            raise InvalidConfigurationError(str(err))
        except IOError as err:
            raise InvalidConfigurationError(str(err))

        self._rsets = {}
        self.default_rset = None
        for name, res_attr in res_config.iteritems():
            self[name] = ResSet(name, res_attr)
            if res_attr.get('default', False):
                if self.default_rset:
                    raise InvalidConfigurationError(
                        'multiple default resource sets configured')
                else:
                    self.default_rset = name 
开发者ID:cea-hpc,项目名称:pcocc,代码行数:21,代码来源:Resources.py

示例8: _read_meta

# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import YAMLError [as 别名]
def _read_meta(self, meta_path, name, revision):
        if not os.path.isfile(meta_path):
            raise ObjectNotFound(name, self._name, revision)

        try:
            with open(meta_path, 'r') as f:
                meta = yaml.safe_load(f)
        except (OSError, IOError) as e:
            raise PcoccError('Unable to get metadata for {0}: {1}'.format(
                    name, e))
        except yaml.YAMLError as e:
            raise PcoccError('Bad metadata for {0}: {1}'.format(
                    name, e))

        try:
            jsonschema.validate(meta,
                                yaml.safe_load(metadata_schema))
        except jsonschema.exceptions.ValidationError as e:
            raise PcoccError('Bad metadata for {0}: {1}'.format(
                    name, e))

        return meta 
开发者ID:cea-hpc,项目名称:pcocc,代码行数:24,代码来源:ObjectStore.py

示例9: _validate_repo_config

# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import YAMLError [as 别名]
def _validate_repo_config(self):
        try:
            with open(self._config_path) as f:
                repo_config = yaml.safe_load(f)
                jsonschema.validate(repo_config,
                                        yaml.safe_load(repo_config_schema))

        except (yaml.YAMLError,
                IOError,
                jsonschema.exceptions.ValidationError) as err:
            raise PcoccError(
                'Bad repository config file {0} : {1}'.format(self._config_path,
                                                                      err))

        if repo_config['version'] != 1:
            raise InvalidConfigurationError(
                'unsupported repository {0} version'.format(self.name)) 
开发者ID:cea-hpc,项目名称:pcocc,代码行数:19,代码来源:ObjectStore.py

示例10: load_task_definition_file

# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import YAMLError [as 别名]
def load_task_definition_file(task_def_file):
    """Open and parse a task-definition file in YAML format."""
    try:
        with open(task_def_file) as f:
            task_def = yaml.safe_load(f)
    except OSError as e:
        raise BenchExecException("Cannot open task-definition file: " + str(e))
    except yaml.YAMLError as e:
        raise BenchExecException("Invalid task definition: " + str(e))

    if str(task_def.get("format_version")) not in ["0.1", "1.0"]:
        raise BenchExecException(
            "Task-definition file {} specifies invalid format_version '{}'.".format(
                task_def_file, task_def.get("format_version")
            )
        )

    return task_def 
开发者ID:sosy-lab,项目名称:benchexec,代码行数:20,代码来源:model.py

示例11: parser

# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import YAMLError [as 别名]
def parser(cls, config_file, logname=__name__):
        logger = logging.getLogger(logname)
        try:
            with open(config_file, 'r') as stream:
                conf = yaml.load(stream)
        except yaml.YAMLError as ex:
            mark = ex.problem_mark
            errormsg = "Error in file: {0} at ({1}, {2})".format(
                config_file,
                mark.line + 1,
                mark.column + 1)
            logger.error(errormsg)
            return None

        if 'dp_id' not in conf:
            errormsg = "dp_id not configured in file: {0}".format(config_file)
            logger.error(errormsg)
            return None

        dp = DP(conf['dp_id'], logname)

        interfaces = conf.pop('interfaces', {})
        vlans = conf.pop('vlans', {})
        acls = conf.pop('acls', {})
        dp.__dict__.update(conf)
        dp.set_defaults()

        for vid, vlan_conf in vlans.iteritems():
            dp.add_vlan(vid, vlan_conf)
        for port_num, port_conf in interfaces.iteritems():
            dp.add_port(port_num, port_conf)
        for acl_num, acl_conf in acls.iteritems():
            dp.add_acl(acl_num, acl_conf)


        return dp 
开发者ID:sdn-ixp,项目名称:iSDX,代码行数:38,代码来源:dp.py

示例12: _Parse

# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import YAMLError [as 别名]
def _Parse(self):
    """Ensure the class data is valid."""
    if self.data is not None:
      try:
        logging.debug('yaml.safe_load(...)')
        self.data.parsed = yaml.safe_load(self.data.data)
      except yaml.YAMLError:
        logging.warning('Error parsing YAML.')
        self.data.parsed = None

      if self.data.parsed is not None:
        try:
          self.data.serial = self.data.parsed.get('serial', None)
          self.data.experiments = self.data.parsed.get('experiments', {})
        except (AttributeError, ExperimentsError):
          logging.warning('Caught exception while parsing self.data.')
          self.data.valid = False
          return

        logging.debug('Parsed YAML data is valid')
        self.data.valid = True
      else:
        logging.debug('Problem parsing YAML data')
        self.data.valid = False
    else:
      logging.error('No data to parse!') 
开发者ID:google,项目名称:macops,代码行数:28,代码来源:experiments.py

示例13: yaml_load

# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import YAMLError [as 别名]
def yaml_load(data):
        try:
            return yaml.load(data)
        except (yaml.YAMLError, AttributeError):
            return None 
开发者ID:Arello-Mobile,项目名称:py2swagger,代码行数:7,代码来源:utils.py

示例14: parse_syntax_file

# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import YAMLError [as 别名]
def parse_syntax_file(self):
        with open(self.syntax_file, 'r') as stream:
            try:
                config = yaml.load(stream)
            except yaml.YAMLError as error:
                print(error)
                return

        self.categories = config['categories']
        self.numbers_color = config['numbers']['color']
        self.strings_color = config['strings']['color']

        self.configure_tags() 
开发者ID:PacktPublishing,项目名称:Tkinter-GUI-Programming-by-Example,代码行数:15,代码来源:highlighter.py

示例15: load_scheme_file

# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import YAMLError [as 别名]
def load_scheme_file(self, scheme):
        with open(scheme, 'r') as stream:
            try:
                config = yaml.load(stream)
            except yaml.YAMLError as error:
                print(error)
                return

        self.foreground = config['foreground']
        self.background = config['background']
        self.text_foreground = config['text_foreground']
        self.text_background = config['text_background'] 
开发者ID:PacktPublishing,项目名称:Tkinter-GUI-Programming-by-Example,代码行数:14,代码来源:texteditor.py


注:本文中的yaml.YAMLError方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。