當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。