本文整理汇总了Python中ruamel.yaml.round_trip_dump方法的典型用法代码示例。如果您正苦于以下问题:Python yaml.round_trip_dump方法的具体用法?Python yaml.round_trip_dump怎么用?Python yaml.round_trip_dump使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类ruamel.yaml
的用法示例。
在下文中一共展示了yaml.round_trip_dump方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: sync
# 需要导入模块: from ruamel import yaml [as 别名]
# 或者: from ruamel.yaml import round_trip_dump [as 别名]
def sync(name, metrics):
"""Write markdown docs"""
metrics_file = Path().resolve().parent / name / "metrics.yaml"
cur = {}
if metrics_file.exists():
cur = yaml.round_trip_load(metrics_file.read_text())
for m in metrics:
entry = cur.setdefault(m.title, asdict(m))
# If the fetched value exists override it, otherwise leave the current one alone.
if m.description:
entry["description"] = m.description
if m.brief:
entry["brief"] = m.brief
if m.metric_type:
entry["metric_type"] = m.metric_type
with metrics_file.open("wt") as f:
yaml.round_trip_dump(cur, f)
示例2: save_yaml
# 需要导入模块: from ruamel import yaml [as 别名]
# 或者: from ruamel.yaml import round_trip_dump [as 别名]
def save_yaml(self, filename: str = None):
"""
Serialize the hierarchy to a file.
:param filename: Target filename, autogenerated if None
"""
if filename is None:
filename = self.config_filename
with tempfile.NamedTemporaryFile('w', dir=os.path.dirname(filename),
delete=False) as temp:
header = self._yaml_header()
if header is not None:
temp.write(header)
yaml.round_trip_dump(self, stream=temp)
tempname = temp.name
os.rename(tempname, filename)
if filename in self.__class__._yaml_cache:
del self.__class__._yaml_cache[filename]
# YAML library configuration
示例3: write_auto_config_data
# 需要导入模块: from ruamel import yaml [as 别名]
# 或者: from ruamel.yaml import round_trip_dump [as 别名]
def write_auto_config_data(
service: str, extra_info: str, data: Dict[str, Any], soa_dir: str = DEFAULT_SOA_DIR
) -> Optional[str]:
"""
Replaces the contents of an automated config file for a service, or creates the file if it does not exist.
Returns the filename of the modified file, or None if no file was written.
"""
service_dir = f"{soa_dir}/{service}"
if not os.path.exists(service_dir):
log.warning(
f"Service {service} does not exist in configs, skipping auto config update"
)
return None
subdir = f"{service_dir}/{AUTO_SOACONFIG_SUBDIR}"
if not os.path.exists(subdir):
os.mkdir(subdir)
filename = f"{subdir}/{extra_info}.yaml"
with open(filename, "w") as f:
content = yaml.round_trip_load(
HEADER_COMMENT.format(regular_filename=f"{service}/{extra_info}.yaml")
)
content.update(data)
f.write(yaml.round_trip_dump(content))
return filename
示例4: import_config
# 需要导入模块: from ruamel import yaml [as 别名]
# 或者: from ruamel.yaml import round_trip_dump [as 别名]
def import_config(args, input_file=None):
if not input_file:
input_file = sys.stdin
source = input_file.read().strip()
if source[0] == "{":
# JSON input
config = json.loads(source)
else:
# YAML input
config = yaml.round_trip_load(source)
STATE["stages"] = config["stages"]
config["config"] = _encrypt_dict(config["config"])
with open(args.config, "wt") as f:
if config:
yaml.round_trip_dump(config, f)
示例5: export_config
# 需要导入模块: from ruamel import yaml [as 别名]
# 或者: from ruamel.yaml import round_trip_dump [as 别名]
def export_config(args, output_file=None):
if not output_file:
output_file = sys.stdout
if os.path.exists(args.config):
with open(args.config, "rt") as f:
config = yaml.round_trip_load(f.read())
STATE["stages"] = config["stages"]
config["config"] = _decrypt_dict(config["config"])
else:
config = {
"stages": {
env["name"]: {"environment": env["name"], "key": "enter-key-name-here"}
for env in STATE["awscreds"].environments
},
"config": {},
}
if args.json:
output_file.write(json.dumps(config, indent=4))
elif config:
yaml.round_trip_dump(config, output_file)
示例6: dump_settings
# 需要导入模块: from ruamel import yaml [as 别名]
# 或者: from ruamel.yaml import round_trip_dump [as 别名]
def dump_settings(settings, file_to_dump):
dumped = False
try:
with open(file_to_dump, 'w') as fp:
yaml.round_trip_dump(settings, fp, indent=2, block_seq_indent=2,
explicit_start=True, default_flow_style=False)
dumped = True
except Exception:
log.exception("Exception dumping upgraded %s: ", file_to_dump)
return dumped
示例7: yaml
# 需要导入模块: from ruamel import yaml [as 别名]
# 或者: from ruamel.yaml import round_trip_dump [as 别名]
def yaml(self) -> str:
"""
Get the YAML representation of this object as a string
"""
return yaml.round_trip_dump(self)
示例8: edit_soa_configs
# 需要导入模块: from ruamel import yaml [as 别名]
# 或者: from ruamel.yaml import round_trip_dump [as 别名]
def edit_soa_configs(filename, instance, cpu, mem, disk):
if not os.path.exists(filename):
filename = filename.replace("marathon", "kubernetes")
if os.path.islink(filename):
real_filename = os.path.realpath(filename)
os.remove(filename)
else:
real_filename = filename
try:
with open(real_filename, "r") as fi:
yams = fi.read()
yams = yams.replace("cpus: .", "cpus: 0.")
data = yaml.round_trip_load(yams, preserve_quotes=True)
instdict = data[instance]
if cpu:
instdict["cpus"] = float(cpu)
if mem:
mem = max(128, round(float(mem)))
instdict["mem"] = mem
if disk:
instdict["disk"] = round(float(disk))
out = yaml.round_trip_dump(data, width=120)
with open(filename, "w") as fi:
fi.write(out)
except FileNotFoundError:
log.exception(f"Could not find {filename}")
except KeyError:
log.exception(f"Error in {filename}. Will continue")
示例9: _resolve_tags
# 需要导入模块: from ruamel import yaml [as 别名]
# 或者: from ruamel.yaml import round_trip_dump [as 别名]
def _resolve_tags(config_file):
"""
Given a templated YAML cloudbuild config file, parse it, resolve image tags
on each build step's image to the corresponding digest, and write new
config with fully qualified images to temporary file for upload to GCS.
Keyword arguments:
config_file -- string representing path to
templated cloudbuild YAML config file
Return value:
path to temporary file containing fully qualified config file, to be
published to GCS.
"""
with open(config_file, 'r') as infile:
logging.info('Templating file: {0}'.format(config_file))
try:
config = yaml.round_trip_load(infile, preserve_quotes=True)
for step in config.get('steps'):
image = step.get('name')
step['name'] = _resolve_tag(image)
args = step.get('args', [])
for i in range(0, len(args)):
arg = args[i]
m = re.search(IMAGE_REGEX, arg)
if m:
suffix = m.group()
prefix = re.sub(suffix, '', arg)
args[i] = prefix + _resolve_tag(suffix)
return yaml.round_trip_dump(config)
except yaml.YAMLError as e:
logging.error(e)
sys.exit(1)
示例10: render_config
# 需要导入模块: from ruamel import yaml [as 别名]
# 或者: from ruamel.yaml import round_trip_dump [as 别名]
def render_config(args, output_file=None):
if not output_file:
output_file = sys.stdout
stages, config = _read_config_file(args)
env = args.environment or args.stage
if args.parameter_store is not None:
return write_to_parameter_store(
env=args.environment or args.stage,
prefix=args.parameter_store,
config=config,
ssm_kms_key=args.ssm_kms_key,
)
if args.json or args.encrypt or args.python:
rendered_config = json.dumps(
config,
indent=None if args.encrypt else 4,
separators=(",", ":") if args.encrypt else (",", ": "),
)
else:
buf = StringIO()
yaml.round_trip_dump(config, buf)
rendered_config = buf.getvalue()
if args.encrypt or args.python:
STATE["stages"] = stages
encrypted_config = []
while rendered_config:
buffer = _encrypt_text(rendered_config[:4096], env)
rendered_config = rendered_config[4096:]
encrypted_config.append(buffer)
if not args.python:
rendered_config = json.dumps(encrypted_config)
else:
rendered_config = f"""ENCRYPTED_CONFIG = {encrypted_config}
import base64
import boto3
import json
def load_config():
config_json = ''
kms = boto3.client('kms')
for buffer in ENCRYPTED_CONFIG:
r = kms.decrypt(CiphertextBlob=base64.b64decode(buffer.encode(
'utf-8')))
config_json += r['Plaintext'].decode('utf-8')
return json.loads(config_json)
CONFIG = load_config()
"""
output_file.write(rendered_config)