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


Python yaml.round_trip_dump方法代码示例

本文整理汇总了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) 
开发者ID:signalfx,项目名称:integrations,代码行数:23,代码来源:cloudsync.py

示例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 
开发者ID:cyanogen,项目名称:uchroma,代码行数:25,代码来源:config.py

示例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 
开发者ID:Yelp,项目名称:paasta,代码行数:27,代码来源:config_utils.py

示例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) 
开发者ID:rackerlabs,项目名称:fleece,代码行数:18,代码来源:config.py

示例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) 
开发者ID:rackerlabs,项目名称:fleece,代码行数:23,代码来源:config.py

示例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 
开发者ID:Cloudbox,项目名称:Community,代码行数:12,代码来源:settings-updater.py

示例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) 
开发者ID:cyanogen,项目名称:uchroma,代码行数:7,代码来源:config.py

示例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") 
开发者ID:Yelp,项目名称:paasta,代码行数:32,代码来源:paasta_update_soa_memcpu.py

示例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) 
开发者ID:GoogleCloudPlatform,项目名称:runtimes-common,代码行数:37,代码来源:template_builder.py

示例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) 
开发者ID:rackerlabs,项目名称:fleece,代码行数:56,代码来源:config.py


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