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


Python yaml.BaseLoader方法代码示例

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


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

示例1: token_or_comment_generator

# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import BaseLoader [as 别名]
def token_or_comment_generator(buffer):
    yaml_loader = yaml.BaseLoader(buffer)

    try:
        prev = None
        curr = yaml_loader.get_token()
        while curr is not None:
            next = yaml_loader.get_token()
            nextnext = (yaml_loader.peek_token()
                        if yaml_loader.check_token() else None)

            yield Token(curr.start_mark.line + 1, curr, prev, next, nextnext)

            for comment in comments_between_tokens(curr, next):
                yield comment

            prev = curr
            curr = next

    except yaml.scanner.ScannerError:
        pass 
开发者ID:adrienverge,项目名称:yamllint,代码行数:23,代码来源:parser.py

示例2:

# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import BaseLoader [as 别名]
def 導入有立繪的角色():
    工程路徑, 臨時立繪文件夾, psd立繪路徑 = 虛擬機環境.工程路徑, 虛擬機環境.臨時立繪文件夾, 虛擬機環境.psd立繪路徑
    try:
        with 讀txt.讀(f'{虛擬機環境.psd立繪路徑}/映射.yaml') as f:
            映射表 = yaml.load(f, Loader=yaml.BaseLoader)
            if 映射表:
                for 角色名 in 映射表:
                    if not os.path.isdir(f'{工程路徑}/{臨時立繪文件夾}/{角色名}'):
                        psd拆包.拆包(f'{psd立繪路徑}/{角色名}.psd', f'{工程路徑}/{臨時立繪文件夾}')
                    logging.info(f'角色「{角色名}」的立繪: \n{映射表[角色名]}')
                    角色(角色名, 映射表[角色名])
            for i in os.listdir(psd立繪路徑):
                if i.endswith('.png'):
                    前名 = os.path.basename(os.path.splitext(i)[0])
                    if not os.path.isdir(f'{工程路徑}/{臨時立繪文件夾}/{前名}'):
                        全名 = os.path.join(psd立繪路徑, i)
                        psd拆包.png假裝拆包(全名, f'{工程路徑}/{臨時立繪文件夾}')
                    角色(前名, {
                        '衣': {'_默認': ['_']},
                        '顏': {'_默認': []},
                    })
    except Exception as e:
        logging.warning('角色立繪沒有導入。')
        logging.exception(e) 
开发者ID:RimoChan,项目名称:Librian,代码行数:26,代码来源:角色.py

示例3: read_yaml

# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import BaseLoader [as 别名]
def read_yaml(self, filepath):
        """
        Read the YAML file at specified location

        return the yaml data on success
        raise an exception upon failure reading/load the file
        """
        try:
            with open(filepath) as fin:
                data = yaml.load(fin, Loader=yaml.BaseLoader)
        except yaml.YAMLError as exc:
            _print("Failed to read {}".format(filepath))
            _print("Error: {}".format(exc))
            return None
        else:
            return data 
开发者ID:CentOS,项目名称:container-pipeline-service,代码行数:18,代码来源:index_reader.py

示例4: read_pipelines

# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import BaseLoader [as 别名]
def read_pipelines(fname):
    absdir=os.path.dirname(os.path.abspath(fname))
    with open(fname) as f:
        pipelines=yaml.load(f, Loader=yaml.BaseLoader)
    for pipeline_name,component_list in pipelines.items():
        new_component_list=[c.format(thisdir=absdir) for c in component_list]
        pipelines[pipeline_name]=new_component_list
    return pipelines 
开发者ID:TurkuNLP,项目名称:Turku-neural-parser-pipeline,代码行数:10,代码来源:full_pipeline_stream.py

示例5: load

# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import BaseLoader [as 别名]
def load(path, withNumbers=True):
    """
    功能:从当前工作目录中加载 YAML 数据库
    输入:路径 path
    输出:yaml 解析器加载后的数据
    """
    return yaml.load(open(path, encoding='utf-8'), Loader=yaml.SafeLoader if withNumbers else yaml.BaseLoader) 
开发者ID:lanluoxiao,项目名称:Chai,代码行数:9,代码来源:tools.py

示例6: loadFromPackage

# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import BaseLoader [as 别名]
def loadFromPackage(path, withNumbers=True):
    """
    功能:从模块包中加载 YAML 数据库
    输入:路径 path
    输出:yaml 解析器加载后的数据
    """
    return yaml.load(pkgutil.get_data(__package__, path).decode(), Loader=yaml.SafeLoader if withNumbers else yaml.BaseLoader) 
开发者ID:lanluoxiao,项目名称:Chai,代码行数:9,代码来源:tools.py

示例7: check_api_params

# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import BaseLoader [as 别名]
def check_api_params(checker: t.Trafaret, loads: Callable[[str], Any] = None,
                     query_param_checker: t.Trafaret = None) -> Any:
    # FIXME: replace ... with [web.Request, Any...] in the future mypy
    def wrap(handler: Callable[..., Awaitable[web.Response]]):

        @functools.wraps(handler)
        async def wrapped(request: web.Request, *args, **kwargs) -> web.Response:
            orig_params: Any
            body: str = ''
            try:
                body_exists = request.can_read_body
                if body_exists:
                    body = await request.text()
                    if request.content_type == 'text/yaml':
                        orig_params = yaml.load(body, Loader=yaml.BaseLoader)
                    else:
                        orig_params = (loads or json.loads)(body)
                else:
                    orig_params = dict(request.query)
                stripped_params = orig_params.copy()
                stripped_params.pop('owner_access_key', None)
                log.debug('stripped raw params: {}', mask_sensitive_keys(stripped_params))
                checked_params = checker.check(stripped_params)
                if body_exists and query_param_checker:
                    query_params = query_param_checker.check(request.query)
                    kwargs['query'] = query_params
            except (json.decoder.JSONDecodeError, yaml.YAMLError, yaml.MarkedYAMLError):
                raise InvalidAPIParameters('Malformed body')
            except t.DataError as e:
                raise InvalidAPIParameters('Input validation error',
                                           extra_data=e.as_dict())
            return await handler(request, checked_params, *args, **kwargs)

        return wrapped

    return wrap 
开发者ID:lablup,项目名称:backend.ai-manager,代码行数:38,代码来源:utils.py

示例8: put

# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import BaseLoader [as 别名]
def put(request: web.Request, params: Any) -> web.Response:
    dbpool = request.app['dbpool']
    template_id = request.match_info['template_id']

    requester_access_key, owner_access_key = await get_access_key_scopes(request, params)
    log.info('PUT (ak:{0}/{1})',
             requester_access_key, owner_access_key if owner_access_key != requester_access_key else '*')

    async with dbpool.acquire() as conn, conn.begin():
        query = (sa.select([session_templates.c.id])
                   .select_from(session_templates)
                   .where((session_templates.c.id == template_id) &
                          (session_templates.c.is_active)
                          ))
        result = await conn.scalar(query)
        if not result:
            raise TaskTemplateNotFound
        try:
            body = json.loads(params['payload'])
        except json.JSONDecodeError:
            body = yaml.load(params['payload'], Loader=yaml.BaseLoader)
        except (yaml.YAMLError, yaml.MarkedYAMLError):
            raise InvalidAPIParameters('Malformed payload')
        body = task_template_v1.check(body)
        query = (sa.update(session_templates)
                   .values(template=body, name=body['metadata']['name'])
                   .where((session_templates.c.id == template_id)))
        result = await conn.execute(query)
        assert result.rowcount == 1

        return web.json_response({'success': True}) 
开发者ID:lablup,项目名称:backend.ai-manager,代码行数:33,代码来源:session_template.py

示例9: load_from_yml_file

# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import BaseLoader [as 别名]
def load_from_yml_file(path):
    with open(path, 'r', encoding='utf-8') as f:
        return yaml.load(f.read(), Loader=BaseYAMLLoader) 
开发者ID:ideascube,项目名称:ideascube,代码行数:5,代码来源:catalog.py

示例10: install

# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import BaseLoader [as 别名]
def install(self, download_path, install_dir):
        super().install(download_path, install_dir)
        print('Adding medias to mediacenter database.')
        root = self.get_root_dir(install_dir)
        manifestfile = Path(root, 'manifest.yml')

        try:
            with manifestfile.open('r') as m:
                manifest = yaml.load(m.read(), Loader=BaseYAMLLoader)

        except FileNotFoundError:
            raise InvalidPackageContent('Missing manifest file in {}'.format(
                self.id))

        os.makedirs(settings.MEDIA_ROOT, exist_ok=True)
        catalog_path = os.path.join(settings.MEDIA_ROOT, "catalog")
        try:
            os.symlink(install_dir, catalog_path)
        except FileExistsError:
            if not os.path.islink(catalog_path):
                printerr("Cannot install package {}. {} must not exist "
                         "or being a symlink.".format(self.id, catalog_path))
                return

        pseudo_install_dir = os.path.join(catalog_path, self.id)
        for media in manifest['medias']:
            try:
                self._install_media(media, pseudo_install_dir)
            except Exception as e:
                # This can lead to installed package with uninstall media.
                # We sould handle this somehow.
                printerr("Cannot install media {} from package {} : {}".format(
                    media['title'], self.id, e))
                continue 
开发者ID:ideascube,项目名称:ideascube,代码行数:36,代码来源:catalog.py

示例11: annLoader

# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import BaseLoader [as 别名]
def annLoader(self):
        data_list = []
        with open(file=self.annFile, mode='r') as fp:
            data_list.extend(yaml.load(fp, Loader=yaml.BaseLoader))
        return data_list 
开发者ID:DeepMotionAIResearch,项目名称:DenseMatchingBenchmark,代码行数:7,代码来源:base.py

示例12: load_training_params

# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import BaseLoader [as 别名]
def load_training_params(path: str) -> ModelParams:
    with open("%s/params.yml" % path, "r") as f:
        params = yaml.load(f, Loader=yaml.BaseLoader)
        return ModelParams(**params) 
开发者ID:PyThaiNLP,项目名称:attacut,代码行数:6,代码来源:utils.py

示例13: __init__

# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import BaseLoader [as 别名]
def __init__(self, cassandra_config=None):
        config_file = pathlib.Path(cassandra_config or self.DEFAULT_CASSANDRA_CONFIG)
        if not config_file.is_file():
            raise RuntimeError('{} is not a file'.format(config_file))
        self._config = yaml.load(config_file.open(), Loader=yaml.BaseLoader) 
开发者ID:thelastpickle,项目名称:cassandra-medusa,代码行数:7,代码来源:cassandra_utils.py

示例14: test_yaml_token_enforcement_no_tokens

# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import BaseLoader [as 别名]
def test_yaml_token_enforcement_no_tokens(self):
        with open('tests/resources/yaml/original/cassandra_no_tokens.yaml', 'r') as f:
            shutil.copyfile('tests/resources/yaml/original/cassandra_no_tokens.yaml',
                            'tests/resources/yaml/work/cassandra_no_tokens.yaml')
        config = configparser.ConfigParser(interpolation=None)
        config['cassandra'] = {
            'config_file': os.path.join(os.path.dirname(__file__), 'resources/yaml/work/cassandra_no_tokens.yaml'),
            'start_cmd': '/etc/init.d/cassandra start',
            'stop_cmd': '/etc/init.d/cassandra stop',
            'is_ccm': '1'
        }

        medusa_config = MedusaConfig(
            storage=None,
            monitoring=None,
            cassandra=_namedtuple_from_dict(CassandraConfig, config['cassandra']),
            ssh=None,
            checks=None,
            logging=None
        )

        cassandra = Cassandra(medusa_config.cassandra)
        tokens = ['1', '2', '3']
        cassandra.replaceTokensInCassandraYamlAndDisableBootstrap(tokens)

        with open('tests/resources/yaml/work/cassandra_no_tokens.yaml', 'r') as f:
            modified_yaml = yaml.load(f, Loader=yaml.BaseLoader)
            self.assertEqual(modified_yaml.get('num_tokens'), '3')
            self.assertEqual(modified_yaml.get('initial_token'), '1,2,3')
            self.assertEqual(modified_yaml.get('auto_bootstrap'), 'false') 
开发者ID:thelastpickle,项目名称:cassandra-medusa,代码行数:32,代码来源:cassandra_utils_test.py

示例15: test_yaml_token_enforcement_with_tokens

# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import BaseLoader [as 别名]
def test_yaml_token_enforcement_with_tokens(self):
        with open('tests/resources/yaml/original/cassandra_with_tokens.yaml', 'r') as f:
            shutil.copyfile('tests/resources/yaml/original/cassandra_with_tokens.yaml',
                            'tests/resources/yaml/work/cassandra_with_tokens.yaml')
        config = configparser.ConfigParser(interpolation=None)
        config['cassandra'] = {
            'config_file': os.path.join(os.path.dirname(__file__), 'resources/yaml/work/cassandra_with_tokens.yaml'),
            'start_cmd': '/etc/init.d/cassandra start',
            'stop_cmd': '/etc/init.d/cassandra stop',
            'is_ccm': '1'
        }

        medusa_config = MedusaConfig(
            storage=None,
            monitoring=None,
            cassandra=_namedtuple_from_dict(CassandraConfig, config['cassandra']),
            ssh=None,
            checks=None,
            logging=None
        )

        cassandra = Cassandra(medusa_config.cassandra)
        tokens = ['1', '2', '3']
        cassandra.replaceTokensInCassandraYamlAndDisableBootstrap(tokens)

        with open('tests/resources/yaml/work/cassandra_with_tokens.yaml', 'r') as f:
            modified_yaml = yaml.load(f, Loader=yaml.BaseLoader)
            self.assertEqual(modified_yaml.get('num_tokens'), '3')
            self.assertEqual(modified_yaml.get('initial_token'), '1,2,3')
            self.assertEqual(modified_yaml.get('auto_bootstrap'), 'false') 
开发者ID:thelastpickle,项目名称:cassandra-medusa,代码行数:32,代码来源:cassandra_utils_test.py


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