本文整理汇总了Python中ruamel.yaml.YAML属性的典型用法代码示例。如果您正苦于以下问题:Python yaml.YAML属性的具体用法?Python yaml.YAML怎么用?Python yaml.YAML使用的例子?那么恭喜您, 这里精选的属性代码示例或许可以为您提供帮助。您也可以进一步了解该属性所在类ruamel.yaml
的用法示例。
在下文中一共展示了yaml.YAML属性的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _read_meta
# 需要导入模块: from ruamel import yaml [as 别名]
# 或者: from ruamel.yaml import YAML [as 别名]
def _read_meta(source) -> Tuple[ZipFile, PluginMeta]:
try:
file = ZipFile(source)
data = file.read("maubot.yaml")
except FileNotFoundError as e:
raise MaubotZipMetaError("Maubot plugin not found") from e
except BadZipFile as e:
raise MaubotZipMetaError("File is not a maubot plugin") from e
except KeyError as e:
raise MaubotZipMetaError("File does not contain a maubot plugin definition") from e
try:
meta_dict = yaml.load(data)
except (YAMLError, KeyError, IndexError, ValueError) as e:
raise MaubotZipMetaError("Maubot plugin definition file is not valid YAML") from e
try:
meta = PluginMeta.deserialize(meta_dict)
except SerializerError as e:
raise MaubotZipMetaError("Maubot plugin definition in file is invalid") from e
return file, meta
示例2: read_meta
# 需要导入模块: from ruamel import yaml [as 别名]
# 或者: from ruamel.yaml import YAML [as 别名]
def read_meta(path: str) -> Optional[PluginMeta]:
try:
with open(os.path.join(path, "maubot.yaml")) as meta_file:
try:
meta_dict = yaml.load(meta_file)
except YAMLError as e:
print(Fore.RED + "Failed to build plugin: Metadata file is not YAML")
print(Fore.RED + str(e) + Fore.RESET)
return None
except FileNotFoundError:
print(Fore.RED + "Failed to build plugin: Metadata file not found" + Fore.RESET)
return None
try:
meta = PluginMeta.deserialize(meta_dict)
except SerializerError as e:
print(Fore.RED + "Failed to build plugin: Metadata file is not valid")
print(Fore.RED + str(e) + Fore.RESET)
return None
return meta
示例3: yaml_dump
# 需要导入模块: from ruamel import yaml [as 别名]
# 或者: from ruamel.yaml import YAML [as 别名]
def yaml_dump(cls, stream=sys.stdout):
class MyRepresenter(SafeRepresenter):
def ignore_aliases(self, data):
return True
yaml = YAML(typ="safe")
yaml.default_flow_style = False
yaml.Representer = MyRepresenter
types = EntityTypeBase.get_entity_types()
for _, t in types.items():
yaml.register_class(t)
yaml.indent(mapping=2, sequence=4, offset=2)
yaml.dump(cls, stream=stream)
示例4: get_api_definition_from_file
# 需要导入模块: from ruamel import yaml [as 别名]
# 或者: from ruamel.yaml import YAML [as 别名]
def get_api_definition_from_file(src_file):
try:
with open(src_file, mode='rb') as f:
api_definition = f.read()
try:
return json.loads(api_definition.decode('utf-8'))
except ValueError as e:
print('Failed to load input as JSON, maybe YAML?')
try:
yaml = YAML(typ='safe')
return yaml.load(api_definition)
except (TypeError, ScannerError) as e:
print('Failed to load input as YAML:{}'.format(e))
raise e
except (Exception, FileNotFoundError):
print('Failed to parse input file, exit')
raise FailedToParseFileException
示例5: to_hour
# 需要导入模块: from ruamel import yaml [as 别名]
# 或者: from ruamel.yaml import YAML [as 别名]
def to_hour(num) -> str:
"""
Convert YAML input to hours
Args:
num: number in YMAL file, e.g., 900, 1700, etc.
Returns:
str
Examples:
>>> to_hour(900)
'09:00'
>>> to_hour(1700)
'17:00'
"""
to_str = str(int(num))
return pd.Timestamp(f'{to_str[:-2]}:{to_str[-2:]}').strftime('%H:%M')
示例6: write_configuration
# 需要导入模块: from ruamel import yaml [as 别名]
# 或者: from ruamel.yaml import YAML [as 别名]
def write_configuration(config_filename, rendered_config, mode=0o600):
'''
Given a target config filename and rendered config YAML, write it out to file. Create any
containing directories as needed.
'''
if os.path.exists(config_filename):
raise FileExistsError('{} already exists. Aborting.'.format(config_filename))
try:
os.makedirs(os.path.dirname(config_filename), mode=0o700)
except (FileExistsError, FileNotFoundError):
pass
with open(config_filename, 'w') as config_file:
config_file.write(rendered_config)
os.chmod(config_filename, mode)
示例7: generate_sample_configuration
# 需要导入模块: from ruamel import yaml [as 别名]
# 或者: from ruamel.yaml import YAML [as 别名]
def generate_sample_configuration(source_filename, destination_filename, schema_filename):
'''
Given an optional source configuration filename, and a required destination configuration
filename, and the path to a schema filename in pykwalify YAML schema format, write out a
sample configuration file based on that schema. If a source filename is provided, merge the
parsed contents of that configuration into the generated configuration.
'''
schema = yaml.round_trip_load(open(schema_filename))
source_config = None
if source_filename:
source_config = load.load_configuration(source_filename)
destination_config = merge_source_configuration_into_destination(
_schema_to_sample_configuration(schema), source_config
)
write_configuration(
destination_filename,
_comment_out_optional_configuration(_render_configuration(destination_config)),
)
示例8: main
# 需要导入模块: from ruamel import yaml [as 别名]
# 或者: from ruamel.yaml import YAML [as 别名]
def main():
yaml = YAML()
opts = parse_args()
source_yaml = yaml.load(Path(opts.source_yaml))
nav_entries = build_api_toc(Path(opts.api_docs_path), Path(opts.docs_root))
# Add version to name.
source_yaml["site_name"] = f"AllenNLP {opts.docs_version}"
# Find the yaml sub-object corresponding to the API table of contents.
site_nav = source_yaml["nav"]
for nav_obj in site_nav:
if API_TOC_KEY in nav_obj:
break
nav_obj[API_TOC_KEY] = nav_entries
with open(opts.target_yaml, "w") as f:
yaml.dump(source_yaml, f)
print(f"{opts.target_yaml} created")
示例9: fix_date_and_remove_null
# 需要导入模块: from ruamel import yaml [as 别名]
# 或者: from ruamel.yaml import YAML [as 别名]
def fix_date_and_remove_null(yaml_file, date, input_type='ruamel'):
"""
Remove the single quotes around the date key-value pair in the provided yaml_file and remove any 'null' values
:param yaml_file: ruamel.yaml instance or location of YAML file
:param date: string date value (e.g. 2019-01-01)
:param input_type: input type can be a ruamel.yaml instance or list
:return: YAML file lines in a list
"""
_yaml = init_yaml()
if input_type == 'ruamel':
# ruamel does not support output to a variable. Therefore we make use of StringIO.
file = StringIO()
_yaml.dump(yaml_file, file)
file.seek(0)
new_lines = file.readlines()
elif input_type == 'list':
new_lines = yaml_file
elif input_type == 'file':
new_lines = yaml_file.readlines()
fixed_lines = [l.replace('\'' + str(date) + '\'', str(date)).replace('null', '')
if REGEX_YAML_DATE.match(l) else
l.replace('null', '') for l in new_lines]
return fixed_lines
示例10: set_yaml_dv_comments
# 需要导入模块: from ruamel import yaml [as 别名]
# 或者: from ruamel.yaml import YAML [as 别名]
def set_yaml_dv_comments(yaml_object):
"""
Set all comments in the detection or visibility YAML object when the 'comment' key-value pair is missing or is None.
This gives the user the flexibility to have YAML files with missing 'comment' key-value pairs.
:param yaml_object: detection or visibility object
:return: detection or visibility object for which empty comments are filled with an empty string
"""
yaml_object['comment'] = yaml_object.get('comment', '')
if yaml_object['comment'] is None:
yaml_object['comment'] = ''
if 'score_logbook' in yaml_object:
for score_obj in yaml_object['score_logbook']:
score_obj['comment'] = score_obj.get('comment', '')
if score_obj['comment'] is None:
score_obj['comment'] = ''
return yaml_object
示例11: get_platform_from_yaml
# 需要导入模块: from ruamel import yaml [as 别名]
# 或者: from ruamel.yaml import YAML [as 别名]
def get_platform_from_yaml(yaml_content):
"""
Read the platform field from the YAML file supporting both string and list values.
:param yaml_content: the content of the YAML file containing the platform field
:return: the platform value
"""
platform = yaml_content.get('platform', None)
if platform is None:
return []
if isinstance(platform, str):
platform = [platform]
platform = [p.lower() for p in platform if p is not None]
if platform == ['all']:
platform = 'all'
else:
valid_platform_list = []
for p in platform:
if p in PLATFORMS.keys():
valid_platform_list.append(PLATFORMS[p])
platform = valid_platform_list
return platform
示例12: _readYaml
# 需要导入模块: from ruamel import yaml [as 别名]
# 或者: from ruamel.yaml import YAML [as 别名]
def _readYaml(self, stream, handleInvalids=True):
"""
Read settings from a YAML stream.
Notes
-----
This is intended to replace the XML stuff as we converge on consistent input formats.
"""
from armi.physics.thermalHydraulics import const # avoid circular import
yaml = YAML()
tree = yaml.load(stream)
if "settings" not in tree:
raise exceptions.InvalidSettingsFileError(
self.inputPath,
"Missing the `settings:` header required in YAML settings",
)
if const.ORIFICE_SETTING_ZONE_MAP in tree:
raise exceptions.InvalidSettingsFileError(
self.inputPath, "Appears to be an orifice_settings file"
)
caseSettings = tree[Roots.CUSTOM]
self.inputVersion = tree["metadata"][Roots.VERSION]
for settingName, settingVal in caseSettings.items():
self._applySettings(settingName, settingVal)
示例13: _readYaml
# 需要导入模块: from ruamel import yaml [as 别名]
# 或者: from ruamel.yaml import YAML [as 别名]
def _readYaml(self, stream):
"""
Read geometry from yaml.
Notes
-----
This is intended to replace the XML format as we converge on
consistent inputs.
"""
yaml = YAML()
tree = yaml.load(stream)
tree = INPUT_SCHEMA(tree)
self.assemTypeByIndices.clear()
for _systemName, system in tree[INP_SYSTEMS].items():
# no need to check for valid since the schema handled that.
self.geomType = system[INP_GEOM]
self.symmetry = system[INP_SYMMETRY]
if INP_DISCRETES in system:
self._read_yaml_discretes(system)
elif INP_LATTICE in system:
self._read_yaml_lattice(system)
示例14: _load_aws_credentials_from_yaml
# 需要导入模块: from ruamel import yaml [as 别名]
# 或者: from ruamel.yaml import YAML [as 别名]
def _load_aws_credentials_from_yaml(yaml_file_path) -> Tuple[str, str]:
with open(yaml_file_path, "r") as yaml_file:
try:
credentials_yaml = YAML().load(yaml_file.read())
except Exception as e:
print(
PaastaColors.red(
"Encountered %s when trying to parse AWS credentials yaml %s. "
"Suppressing further output to avoid leaking credentials."
% (type(e), yaml_file_path)
)
)
sys.exit(1)
return (
credentials_yaml["aws_access_key_id"],
credentials_yaml["aws_secret_access_key"],
)
示例15: get_devices_conn_params
# 需要导入模块: from ruamel import yaml [as 别名]
# 或者: from ruamel.yaml import YAML [as 别名]
def get_devices_conn_params() -> Dict[str, Dict[str, str]]:
"""Creates a dictionary of connection parameters for SSH"""
result: Dict[str, Dict[str, str]] = {}
yaml = YAML()
with open(HOSTS_FILE, 'r') as f:
hosts = yaml.load(f)
for device, device_details in hosts["devices"]["routers"].items():
device_params = {
"host": device_details["host"],
"username": DEVICE_USERNAME,
"password": DEVICE_PASSWORD,
"device_type": DEVICE_TYPE,
"timeout": CONNECTION_TIMEOUT,
"global_delay_factor": constants.NETMIKO_GLOBAL_DELAY_FACTOR,
}
result[device] = device_params
return result