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


Python yaml.CLoader方法代码示例

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


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

示例1: _download_results

# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import CLoader [as 别名]
def _download_results(config, _blob_client, out_path, count, ptrn=FOLD_FILE_PATTERN):

    pathlib.Path(config.BATCH_DIRECTORY).mkdir(parents=True, exist_ok=True)
    blob_names = [b.name for b in _blob_client.list_blobs(config.CONTAINER_NAME)]

    results = []
    for i in range(count):
        blob_name = ptrn.format(i)
        if not blob_name in blob_names:
            raise RuntimeError("incomplete blob set: missing blob {}".format(blob_name))
        out_path = os.path.join(config.BATCH_DIRECTORY, blob_name)
        with _blob_client.get_blob_to_stream(
            config.CONTAINER_NAME, blob_name, out_path
        ) as blob:
            results[i] = load(blob, Loader=Loader)
    return results 
开发者ID:microsoft,项目名称:SparseSC,代码行数:18,代码来源:azure_batch_client.py

示例2: get_config

# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import CLoader [as 别名]
def get_config(infile):
    """
    read in the contents of the inputs yaml file
    """

    with open(infile, "r") as fp:
        config = load(fp, Loader=Loader)
    try:
        v_pen = tuple(config["v_pen"])
    except TypeError:
        v_pen = (config["v_pen"],)

    try:
        w_pen = tuple(config["w_pen"])
    except TypeError:
        w_pen = (config["w_pen"],)

    return v_pen, w_pen, config 
开发者ID:microsoft,项目名称:SparseSC,代码行数:20,代码来源:stt.py

示例3: is_roll_back

# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import CLoader [as 别名]
def is_roll_back(update: dict):
    """
    check if the new update is actually a rollback one
    """
    codename = update['codename']
    version = update['version']
    filename = update['filename']
    branch = get_branch(version)
    rom_type = get_type(filename).lower()
    try:
        with open(f'archive/{branch}_{rom_type}/{codename}.yml', 'r') as yaml_file:
            data = yaml.load(yaml_file, Loader=yaml.CLoader)
            versions = list(data[codename].keys())
        return bool(version in versions)
    except FileNotFoundError:
        return False 
开发者ID:XiaomiFirmwareUpdater,项目名称:miui-updates-tracker,代码行数:18,代码来源:utils.py

示例4: archive

# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import CLoader [as 别名]
def archive(update: dict):
    """Append new update to the archive"""
    codename = update['codename']
    link = update['download']
    version = update['version']
    branch = get_branch(version)
    rom_type = 'recovery' if update['filename'].endswith('.zip') else 'fastboot'
    try:
        with open(f'archive/{branch}_{rom_type}/{codename}.yml', 'r') as yaml_file:
            data = yaml.load(yaml_file, Loader=yaml.CLoader)
            data[codename].update({version: link})
            data.update({codename: data[codename]})
            with open(f'archive/{branch}_{rom_type}/{codename}.yml', 'w') as output:
                yaml.dump(data, output, Dumper=yaml.CDumper)
    except FileNotFoundError:
        data = {codename: {version: link}}
        with open(f'archive/{branch}_{rom_type}/{codename}.yml', 'w') as output:
            yaml.dump(data, output, Dumper=yaml.CDumper) 
开发者ID:XiaomiFirmwareUpdater,项目名称:miui-updates-tracker,代码行数:20,代码来源:tracker.py

示例5: merge_archive

# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import CLoader [as 别名]
def merge_archive():
    """
    merge all archive yaml files into one file
    """
    print("Creating archive YAML files")
    for name in ['stable_recovery', 'stable_fastboot', 'weekly_recovery', 'weekly_fastboot']:
        yaml_files = [x for x in sorted(glob(f'archive/{name}/*.yml'))
                      if not x.endswith('recovery.yml')
                      and not x.endswith('fastboot.yml')]
        yaml_data = []
        for file in yaml_files:
            with open(file, "r") as yaml_file:
                yaml_data.append(yaml.load(yaml_file, Loader=yaml.CLoader))
        with open(f'archive/{name}/{name}', "w") as output:
            yaml.dump(yaml_data, output, Dumper=yaml.CDumper)
        if path.exists(f'archive/{name}/{name}'):
            rename(f'archive/{name}/{name}', f'archive/{name}/{name}.yml') 
开发者ID:XiaomiFirmwareUpdater,项目名称:miui-updates-tracker,代码行数:19,代码来源:tracker.py

示例6: __init__

# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import CLoader [as 别名]
def __init__(self,filename=None):
        self.joint_p = []
        self.joint_v = []
        self.joint_t = []
        self.gripper_cmd = []
        self.gripper_t = []
        self.tform = {}
        self.world_t = []

        if not filename==None:
            stream = file(filename,'r')
            demo = yaml.load(stream,Loader=Loader)
            self.joint_p = demo.joint_p
            self.joint_v = demo.joint_v
            self.joint_t = demo.joint_t
            self.gripper_cmd = demo.gripper_cmd
            self.tform = demo.tform
            self.world_t = demo.world_t 
开发者ID:jhu-lcsr,项目名称:costar_plan,代码行数:20,代码来源:types.py

示例7: parse_yaml_file

# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import CLoader [as 别名]
def parse_yaml_file(file: TextIOWrapper) -> Optional[dict]:
    """Parses a YAML file and returns a nested dictionary containing its contents.

    :param file: Handle of file to parse
    :return: Parsed file contents"""
    try:
        # Parses the YAML file into a dict
        return load(file, Loader=Loader)
    except YAMLError as exc:
        logging.critical("Could not parse YAML file %s", file.name)
        if hasattr(exc, 'problem_mark'):
            # Tell user exactly where the syntax error is
            mark = exc.problem_mark
            logging.error("Error position: (%s:%s)",
                          mark.line + 1, mark.column + 1)
        else:
            logging.error("Error: %s", exc)
            return None


# PyYAML Reference: http://pyyaml.org/wiki/PyYAMLDocumentation 
开发者ID:GhostofGoes,项目名称:ADLES,代码行数:23,代码来源:parser.py

示例8: parse_yaml

# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import CLoader [as 别名]
def parse_yaml(filename: str) -> Optional[dict]:
    """Parses a YAML file and returns a nested dictionary containing its contents.

    :param filename: Name of YAML file to parse
    :return: Parsed file contents"""
    try:
        # Enables use of stdin if '-' is specified
        with sys.stdin if filename == '-' else open(filename) as f:
            try:
                # Parses the YAML file into a dict
                return load(f, Loader=Loader)
            except YAMLError as exc:
                logging.critical("Could not parse YAML file %s", filename)
                if hasattr(exc, 'problem_mark'):
                    # Tell user exactly where the syntax error is
                    mark = exc.problem_mark
                    logging.error("Error position: (%s:%s)",
                                  mark.line + 1, mark.column + 1)
                else:
                    logging.error("Error: %s", exc)
                    return None
    except FileNotFoundError:
        logging.critical("Could not find YAML file for parsing: %s", filename)
        return None 
开发者ID:GhostofGoes,项目名称:ADLES,代码行数:26,代码来源:parser.py

示例9: loads

# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import CLoader [as 别名]
def loads(self, s, force_document_comment_to_first_entry=False, with_comments=False):
        if not with_comments:  # don't care about first comment if we don't care about coments globaly
            force_document_comment_to_first_entry = False
        if force_document_comment_to_first_entry:
            s = '____useless_property: true\n' + s
        yamllib = self.get_yaml_lib(with_comments)
        if with_comments:
            data = yamllib.round_trip_load(s)
        else:
            # The yaml lib do not manage loads, so need to fake it first
            StringIO = libstore.get_StringIO_unicode_compatible()
            fake_file = StringIO(s)  # unicode_to_bytes(s))
            if simple_yaml_loader is not None:
                data = yamllib.load(fake_file, Loader=simple_yaml_loader)
            else:
                data = yamllib.round_trip_load(s)
        if force_document_comment_to_first_entry:
            del data['____useless_property']
        return data 
开发者ID:naparuba,项目名称:opsbro,代码行数:21,代码来源:yamlmgr.py

示例10: create_papers

# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import CLoader [as 别名]
def create_papers(srcdir, clean=False):
    """Creates page stubs for all papers in the Anthology."""
    log.info("Creating stubs for papers...")
    if not check_directory("{}/content/papers".format(srcdir), clean=clean):
        return

    # Go through all paper volumes
    for yamlfile in tqdm(glob("{}/data/papers/*.yaml".format(srcdir))):
        log.debug("Processing {}".format(yamlfile))
        with open(yamlfile, "r") as f:
            data = yaml.load(f, Loader=Loader)
        # Create a paper stub for each entry in the volume
        for anthology_id, entry in data.items():
            paper_dir = "{}/content/papers/{}".format(srcdir, anthology_id.split("-")[0])
            if not os.path.exists(paper_dir):
                os.makedirs(paper_dir)
            with open("{}/{}.md".format(paper_dir, anthology_id), "w") as f:
                print("---", file=f)
                yaml.dump(
                    {"anthology_id": anthology_id, "title": entry["title"]},
                    default_flow_style=False,
                    stream=f,
                )
                print("---", file=f) 
开发者ID:acl-org,项目名称:acl-anthology,代码行数:26,代码来源:create_hugo_pages.py

示例11: create_people

# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import CLoader [as 别名]
def create_people(srcdir, clean=False):
    """Creates page stubs for all authors/editors in the Anthology."""
    log.info("Creating stubs for people...")
    if not check_directory("{}/content/people".format(srcdir), clean=clean):
        return

    for yamlfile in tqdm(glob("{}/data/people/*.yaml".format(srcdir))):
        log.debug("Processing {}".format(yamlfile))
        with open(yamlfile, "r") as f:
            data = yaml.load(f, Loader=Loader)
        # Create a page stub for each person
        for name, entry in data.items():
            person_dir = "{}/content/people/{}".format(srcdir, name[0])
            if not os.path.exists(person_dir):
                os.makedirs(person_dir)
            yaml_data = {"name": name, "title": entry["full"], "lastname": entry["last"]}
            with open("{}/{}.md".format(person_dir, name), "w") as f:
                print("---", file=f)
                # "lastname" is dumped to allow sorting by it in Hugo
                yaml.dump(yaml_data, default_flow_style=False, stream=f)
                print("---", file=f)

    return data 
开发者ID:acl-org,项目名称:acl-anthology,代码行数:25,代码来源:create_hugo_pages.py

示例12: create_sigs

# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import CLoader [as 别名]
def create_sigs(srcdir, clean=False):
    """Creates page stubs for all SIGs in the Anthology."""
    yamlfile = "{}/data/sigs.yaml".format(srcdir)
    log.debug("Processing {}".format(yamlfile))
    with open(yamlfile, "r") as f:
        data = yaml.load(f, Loader=Loader)

    log.info("Creating stubs for SIGs...")
    if not check_directory("{}/content/sigs".format(srcdir), clean=clean):
        return
    # Create a paper stub for each SIGS (e.g. SIGMORPHON)
    for sig, sig_data in data.items():
        sig_str = sig_data["slug"]
        with open("{}/content/sigs/{}.md".format(srcdir, sig_str), "w") as f:
            print("---", file=f)
            yaml.dump(
                {
                    "acronym": sig,
                    "short_acronym": sig[3:] if sig.startswith("SIG") else sig,
                    "title": sig_data["name"],
                },
                default_flow_style=False,
                stream=f,
            )
            print("---", file=f) 
开发者ID:acl-org,项目名称:acl-anthology,代码行数:27,代码来源:create_hugo_pages.py

示例13: load_results_sixd17

# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import CLoader [as 别名]
def load_results_sixd17(path):
    """
    Loads 6D object pose estimates from a file.

    :param path: Path to a file with poses.
    :return: List of the loaded poses.
    """
    with open(path, "r") as f:
        res = yaml.load(f, Loader=yaml.CLoader)
        if not res["ests"] or res["ests"] == [{}]:
            res["ests"] = []
        else:
            for est in res["ests"]:
                est["R"] = np.array(est["R"]).reshape((3, 3))
                est["t"] = np.array(est["t"]).reshape((3, 1))
                if isinstance(est["score"], str):
                    if "nan" in est["score"]:
                        est["score"] = 0.0
                    else:
                        raise ValueError("Bad type of score.")
    return res 
开发者ID:liyi14,项目名称:mx-DeepIM,代码行数:23,代码来源:inout.py

示例14: load_app_from_config

# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import CLoader [as 别名]
def load_app_from_config(path):
    """
    Generate app directly from config file, bypassing command line settings (useful for testing in ipython)
    """
    Setting.generate_missing_shorthands()
    defaults = Setting.generate_defaults_dict()
    if osp.isfile(path):
        file_stream = open(path, "r", encoding="utf-8")
        config_defaults = load(file_stream, Loader=Loader)
        file_stream.close()
        for key, value in config_defaults.items():
            defaults[key] = value
    else:
        raise ValueError("Settings file not found at: {0:s}".format(path))
    args = ap.Namespace()
    for key, value in defaults.items():
        args.__dict__[key] = value

    app = StereoMatcherApp(args)

    return app 
开发者ID:Algomorph,项目名称:cvcalib,代码行数:23,代码来源:stereo.py

示例15: load_app_from_config

# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import CLoader [as 别名]
def load_app_from_config(path):
    """
    Generate app directly from config file, bypassing command line settings (useful for testing in ipython)
    """
    Setting.generate_missing_shorthands()
    defaults = Setting.generate_defaults_dict()
    if osp.isfile(path):
        file_stream = open(path, "r", encoding="utf-8")
        config_defaults = load(file_stream, Loader=Loader)
        file_stream.close()
        for key, value in config_defaults.items():
            defaults[key] = value
    else:
        raise ValueError("Settings file not found at: {0:s}".format(path))
    args = ap.Namespace()
    for key, value in defaults.items():
        args.__dict__[key] = value
    if args.unsynced:
        app = ApplicationUnsynced(args)
    else:
        app = ApplicationSynced(args)
    return app 
开发者ID:Algomorph,项目名称:cvcalib,代码行数:24,代码来源:calibrate.py


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