shyaml.py 文件源码

python
阅读 29 收藏 0 点赞 0 评论 0

项目:smarthome 作者: smarthomeNG 项目源码 文件源码
def yaml_load(filename, ordered=False, ignore_notfound=False):
    """
    Load contents of a configuration file into an dict/OrderedDict structure. The configuration file has to be a valid yaml file

    :param filename: name of the yaml file to load
    :type filename: str
    :param ordered: load to an OrderedDict? Default=False
    :type ordered: bool

    :return: configuration data loaded from the file (or None if an error occured)
    :rtype: Dict | OrderedDict | None
    """

    dict_type = 'dict'
    if ordered:
        dict_type = 'OrderedDict'
    logger.info("Loading '{}' to '{}'".format(filename, dict_type))
    y = None

    try:
        with open(filename, 'r') as stream:
            sdata = stream.read()
        sdata = sdata.replace('\n', '\n\n')
        if ordered:
            y = _ordered_load(sdata, yaml.SafeLoader)
        else:
            y = yaml.load(sdata, yaml.SafeLoader)
    except Exception as e:
        estr = str(e)
        if "found character '\\t'" in estr:
            estr = estr[estr.find('line'):]
            estr = 'TABs are not allowed in YAML files, use spaces for indentation instead!\nError in ' + estr
        if ("while scanning a simple key" in estr) and ("could not found expected ':'" in estr):
            estr = estr[estr.find('column'):estr.find('could not')]
            estr = 'The colon (:) following a key has to be followed by a space. The space is missing!\nError in ' + estr
        if "[Errno 2]" in estr:
            if not ignore_notfound:
                logger.warning("YAML-file not found: {}".format(filename))
        else:
            logger.error("YAML-file load error in {}:  \n{}".format(filename, estr))

    return y
评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号