當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。