本文整理匯總了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
示例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)
示例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
示例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
示例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)
示例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)
示例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
示例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})
示例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)
示例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
示例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
示例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)
示例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)
示例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')
示例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')