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


Python yaml.dump方法代码示例

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


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

示例1: make_query_loop

# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import dump [as 别名]
def make_query_loop(tmpdir, config_data, registry):
    query_loops = []

    def make_loop():
        config_file = tmpdir / "config.yaml"
        config_file.write_text(yaml.dump(config_data), "utf-8")
        with config_file.open() as fh:
            config = load_config(fh, logging.getLogger())
        registry.create_metrics(config.metrics.values())
        query_loop = loop.QueryLoop(config, registry, logging)
        query_loops.append(query_loop)
        return query_loop

    yield make_loop
    await asyncio.gather(
        *(query_loop.stop() for query_loop in query_loops), return_exceptions=True,
    ) 
开发者ID:albertodonato,项目名称:query-exporter,代码行数:19,代码来源:test_loop.py

示例2: make_model_yaml

# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import dump [as 别名]
def make_model_yaml(template_yaml, model_json, output_yaml_path):
    #
    with open(template_yaml, 'r') as f:
        model_yaml = yaml.load(f)
    #
    # get the model config:
    json_file = open(model_json, 'r')
    loaded_model_json = json_file.read()
    json_file.close()
    loaded_model = keras.models.model_from_json(loaded_model_json)
    #
    model_yaml["schema"]["targets"] = []
    for oname, oshape in zip(loaded_model.output_names, loaded_model.output_shape):
        append_el ={"name":oname , "shape":str(oshape)#replace("None,", "")
        , "doc":"Methylation probability for %s"%oname}
        model_yaml["schema"]["targets"].append(append_el)
    #
    with open(output_yaml_path, 'w') as f:
        yaml.dump(model_yaml, f, default_flow_style=False) 
开发者ID:kipoi,项目名称:models,代码行数:21,代码来源:prepare_model_yaml.py

示例3: make_secondary_dl_yaml

# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import dump [as 别名]
def make_secondary_dl_yaml(template_yaml, model_json, output_yaml_path):
    with open(template_yaml, 'r') as f:
        model_yaml = yaml.load(f)
    #
    # get the model config:
    json_file = open(model_json, 'r')
    loaded_model_json = json_file.read()
    json_file.close()
    loaded_model = keras.models.model_from_json(loaded_model_json)
    #
    model_yaml["output_schema"]["targets"] = []
    for oname, oshape in zip(loaded_model.output_names, loaded_model.output_shape):
        append_el ={"name":oname , "shape":str(oshape)#replace("None,", "")
        , "doc":"Methylation probability for %s"%oname}
        model_yaml["output_schema"]["targets"].append(append_el)
    #
    with open(output_yaml_path, 'w') as f:
        yaml.dump(model_yaml, f, default_flow_style=False) 
开发者ID:kipoi,项目名称:models,代码行数:20,代码来源:prepare_model_yaml.py

示例4: _updateBundle

# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import dump [as 别名]
def _updateBundle(self, operatorBundle, file_name, yaml_string):
        # Determine which operator file type the yaml is
        operator_artifact = identify.get_operator_artifact_type(yaml_string)

        # If the file isn't one of our special types, we ignore it and return
        if operator_artifact == identify.UNKNOWN_FILE:
            return operatorBundle

        # Get the array name expected by the dictionary for the given file type
        op_artifact_plural = operator_artifact[0:1].lower() + operator_artifact[1:] + 's'

        # Marshal the yaml into a dictionary
        yaml_data = yaml.safe_load(yaml_string)

        # Add the data dictionary to the correct list
        operatorBundle["data"][op_artifact_plural].append(yaml_data)

        # Encode the dictionary into a string, then use that as a key to reference
        # the file name associated with that yaml file. Then add it to the metadata.
        if file_name != "":
            unencoded_yaml = yaml.dump(yaml_data)
            relative_path = self._get_relative_path(file_name)
            operatorBundle["metadata"]["filenames"][hash(unencoded_yaml)] = relative_path

        return operatorBundle 
开发者ID:operator-framework,项目名称:operator-courier,代码行数:27,代码来源:build.py

示例5: Dump

# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import dump [as 别名]
def Dump(path: Text, data: Any, mode: Text = 'w'):
  """Write a config file containing some data.

  Args:
    path: The filesystem path to the destination file.
    data: Data to be written to the file as yaml.
    mode: Mode to use for writing the file (default: w)
  """
  file_util.CreateDirectories(path)
  tmp_f = path + '.tmp'
  # Write to a .tmp file to avoid corrupting the original if aborted mid-way.
  try:
    with open(tmp_f, mode) as handle:
      handle.write(yaml.dump(data))
  except IOError as e:
    raise Error('Could not save data to yaml file %s: %s' % (path, str(e)))
  # Replace the original with the tmp.
  try:
    file_util.Move(tmp_f, path)
  except file_util.Error as e:
    raise Error('Could not replace config file. (%s)' % str(e)) 
开发者ID:google,项目名称:glazier,代码行数:23,代码来源:files.py

示例6: test_collect_yaml_permission_errors

# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import dump [as 别名]
def test_collect_yaml_permission_errors(tmpdir, kind):
    a = {'x': 1, 'y': 2}
    b = {'y': 3, 'z': 4}

    dir_path = str(tmpdir)
    a_path = os.path.join(dir_path, 'a.yaml')
    b_path = os.path.join(dir_path, 'b.yaml')

    with open(a_path, mode='w') as f:
        yaml.dump(a, f)
    with open(b_path, mode='w') as f:
        yaml.dump(b, f)

    if kind == 'directory':
        cant_read = dir_path
        expected = {}
    else:
        cant_read = a_path
        expected = b
    with no_read_permissions(cant_read):
        config = merge(*collect_yaml(paths=[dir_path]))
        assert config == expected 
开发者ID:NCAR,项目名称:esmlab,代码行数:24,代码来源:test_config.py

示例7: test_collect

# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import dump [as 别名]
def test_collect():
    a = {'x': 1, 'y': {'a': 1}}
    b = {'x': 2, 'z': 3, 'y': {'b': 2}}
    env = {'ESMLAB_W': 4}

    expected = {'w': 4, 'x': 2, 'y': {'a': 1, 'b': 2}, 'z': 3}

    with tmpfile(extension='yaml') as fn1:
        with tmpfile(extension='yaml') as fn2:
            with open(fn1, 'w') as f:
                yaml.dump(a, f)
            with open(fn2, 'w') as f:
                yaml.dump(b, f)

            config = collect([fn1, fn2], env=env)
            assert config == expected 
开发者ID:NCAR,项目名称:esmlab,代码行数:18,代码来源:test_config.py

示例8: test_ensure_file_defaults_to_ESMLAB_CONFIG_directory

# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import dump [as 别名]
def test_ensure_file_defaults_to_ESMLAB_CONFIG_directory(tmpdir):
    a = {'x': 1, 'y': {'a': 1}}
    source = os.path.join(str(tmpdir), 'source.yaml')
    with open(source, 'w') as f:
        yaml.dump(a, f)

    destination = os.path.join(str(tmpdir), 'esmlab')
    PATH = esmlab.config.PATH
    try:
        esmlab.config.PATH = destination
        ensure_file(source=source)
    finally:
        esmlab.config.PATH = PATH

    assert os.path.isdir(destination)
    [fn] = os.listdir(destination)
    assert os.path.split(fn)[1] == os.path.split(source)[1] 
开发者ID:NCAR,项目名称:esmlab,代码行数:19,代码来源:test_config.py

示例9: get_config

# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import dump [as 别名]
def get_config(config_file, exp_dir=None):
  """ Construct and snapshot hyper parameters """
  config = edict(yaml.load(open(config_file, 'r')))

  # create hyper parameters
  config.run_id = str(os.getpid())
  config.exp_name = '_'.join([
      config.model.name, config.dataset.name,
      time.strftime('%Y-%b-%d-%H-%M-%S'), config.run_id
  ])

  if exp_dir is not None:
    config.exp_dir = exp_dir

  config.save_dir = os.path.join(config.exp_dir, config.exp_name)

  # snapshot hyperparameters
  mkdir(config.exp_dir)
  mkdir(config.save_dir)

  save_name = os.path.join(config.save_dir, 'config.yaml')
  yaml.dump(edict2dict(config), open(save_name, 'w'), default_flow_style=False)

  return config 
开发者ID:lrjconan,项目名称:LanczosNetwork,代码行数:26,代码来源:arg_helper.py

示例10: convert_legacy_template

# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import dump [as 别名]
def convert_legacy_template(path):
    with open(path) as f:
        ta = f.read().strip().split('\n\n')

    groups = [parse_group(g) for g in ta]
    data = {'groups': [group_to_dict(g) for g in groups]}

    new_path = path[:-3] + 'yml'
    warning = ''
    if p.isfile(new_path):
        new_path = path[:-4] + '-converted.yml'
        warning = '(appended -converted to avoid collision)'

    with open(new_path, 'w') as nf:
        yaml.dump(data, nf, indent=4,  default_flow_style=False)

    os.remove(path)

    print " - {} > {} {}".format(path, new_path, warning) 
开发者ID:menpo,项目名称:landmarkerio-server,代码行数:21,代码来源:template.py

示例11: generate_yaml

# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import dump [as 别名]
def generate_yaml(self):
        data = dict(
            meta=dict(
                author="Zack",
                enabled=True,
                name="EXAMPLE.yaml",
                description="Description"
            ),
            tests=[dict(
                rule_id=1234,
                stages=[dict(
                    stage=dict(
                        input=self.input,
                        output=dict(
                            status=200
                        )
                    )
                )]
            )]
        )
        return yaml.dump(data, default_flow_style=False) 
开发者ID:CRS-support,项目名称:ftw,代码行数:23,代码来源:request_to_yaml.py

示例12: toYAML

# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import dump [as 别名]
def toYAML(self, **options):
        """ Serializes this Munch to YAML, using `yaml.safe_dump()` if
            no `Dumper` is provided. See the PyYAML documentation for more info.

            >>> b = Munch(foo=['bar', Munch(lol=True)], hello=42)
            >>> import yaml
            >>> yaml.safe_dump(b, default_flow_style=True)
            '{foo: [bar, {lol: true}], hello: 42}\\n'
            >>> b.toYAML(default_flow_style=True)
            '{foo: [bar, {lol: true}], hello: 42}\\n'
            >>> yaml.dump(b, default_flow_style=True)
            '!munch.Munch {foo: [bar, !munch.Munch {lol: true}], hello: 42}\\n'
            >>> b.toYAML(Dumper=yaml.Dumper, default_flow_style=True)
            '!munch.Munch {foo: [bar, !munch.Munch {lol: true}], hello: 42}\\n'

        """
        opts = dict(indent=4, default_flow_style=False)
        opts.update(options)
        if 'Dumper' not in opts:
            return yaml.safe_dump(self, **opts)
        else:
            return yaml.dump(self, **opts) 
开发者ID:remg427,项目名称:misp42splunk,代码行数:24,代码来源:__init__.py

示例13: save_objects_to_file

# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import dump [as 别名]
def save_objects_to_file(file_name, data_dict):
    """Write the network devices out to a file."""

    # Determine whether .pkl, .yml, or .json file
    if file_name.count(".") == 1:
        _, out_format = file_name.split(".")
    else:
        raise ValueError("Invalid file name: {}".format(file_name))

    if out_format == 'pkl':
        with open(file_name, 'wb') as f:
            pickle.dump(data_dict, f)
    elif out_format == 'yml':
        with open(file_name, 'w') as f:
            f.write(yaml.dump(data_dict, default_flow_style=False))
    elif out_format == 'json':
        with open(file_name, 'w') as f:
            json.dump(data_dict, f) 
开发者ID:ktbyers,项目名称:python_course,代码行数:20,代码来源:ex1_run_config_chg.py

示例14: output_yaml

# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import dump [as 别名]
def output_yaml(links, prefix=""):
    test_dict = {}
    for test_name in links.keys():
        default_name = get_name(prefix, test_name, links[test_name].action, links[test_name].url)
        test_dict["test_name"] = default_name

        request = {"url": links[test_name].url, "method": str.upper(links[test_name].action)}

        if links[test_name].encoding:
            request["headers"] = {"content-type": links[test_name].encoding}

        json = get_request_placeholders(links[test_name].fields)
        if json and request["method"] != "GET":
            request["json"] = json

        response = {"strict": False, "status_code": 200}
        inner_dict = {"name": default_name, "request": request, "response": response}

        test_dict["stages"] = [inner_dict]
        print(yaml.dump(test_dict, explicit_start=True, default_flow_style=False)) 
开发者ID:mozilla,项目名称:normandy,代码行数:22,代码来源:generate_from_openapi.py

示例15: GenerateConfig

# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import dump [as 别名]
def GenerateConfig(context):
    config = {'resources': []}

    # A zonal vm_multiple_instances resource for each zone in the properties list.
    for zone in context.properties['zones']:
        new_properties = copy.deepcopy(context.properties)
        new_properties['zone'] = zone
        service = {
            'name': context.env['deployment'] + '-' + zone,
            'type': 'vm_multiple_instances.py',
            'properties': new_properties
        }

        config['resources'].append(service)

    return yaml.dump(config) 
开发者ID:DSPN,项目名称:google-compute-engine-dse,代码行数:18,代码来源:regional_multi_vm.py


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