使用PyYaml将集合导出到YAML文件

-1 投票
1 回答
4299 浏览
提问于 2025-04-16 01:12

我正在写一个Python应用程序,想把我的Python对象转换成YAML格式,使用的是PyYaml库。我用的是Python 2.6,运行在Ubuntu Lucid 10.04上。我在Ubuntu中使用的PyYAML包可以在这里找到:http://packages.ubuntu.com/lucid/python/python-yaml

我的对象有3个文本变量和一个对象列表,大概是这样的:

ClassToDump:

   #3 text variables
   text_variable_1
   text_variable_2
   text_variable_3
   #a list of AnotherObjectsClass instances
   list_of_another_objects = [object1,object2,object3]


AnotherObjectsClass:
   text_variable_1
   text_variable_2
   text_variable_3

我想转换的这个类包含了一些AnotherObjectClass实例的列表,而这个类也有几个文本变量。

但是,PyYaml似乎没有把AnotherObjectClass实例中的集合转换出来。PyYAML确实把text_variable_1、text_variable_2和text_variable_3转换了。

我使用以下的pyYaml API来转换ClassToDump实例:

classToDump = ClassToDump();
yaml.dump(ClassToDump,yaml_file_to_dump)

有没有人有过把对象列表转换成YAML的经验?

这是实际的完整代码片段:

def write_config(file_path,class_to_dump):    
    config_file = open(file_path,'w');  
    yaml.dump(class_to_dump,config_file);

def dump_objects():

rule = Miranda.Rule();
rule.rule_condition = Miranda.ALL
rule.rule_setting = ruleSetting
rule.rule_subjects.append(rule1)
rule.rule_subjects.append(rule2)
rule.rule_verb = ruleVerb

write_config(rule ,'./config.yaml');

这是输出结果:

!!python/object:Miranda.Rule rule_condition: ALL rule_setting: !!python/object:Miranda.RuleSetting {confirm_action: true, description: My Configuration, enabled: true, recursive: true, source_folder: source_folder} rule_verb: !!python/object:Miranda.RuleVerb {compression: true, dest_folder: /home/zainul/Downloads, type: Move File}

1 个回答

2

PyYaml模块会为你处理好所有细节,希望下面这段代码能帮到你。

import sys
import yaml

class AnotherClass:
    def __init__(self):
        pass

class MyClass:
    def __init__(self):
        self.text_variable_1 = 'hello'
        self.text_variable_2 = 'world'
        self.text_variable_3 = 'foobar'
        self.list_of_another_objects = [
            AnotherClass(),
            AnotherClass(),
            AnotherClass()
        ]

obj = MyClass()
yaml.dump(obj, sys.stdout)

这段代码的输出结果是:

!!python/object:__main__.MyClass
list_of_another_objects:
- !!python/object:__main__.AnotherClass {}
- !!python/object:__main__.AnotherClass {}
- !!python/object:__main__.AnotherClass {}
text_variable_1: hello
text_variable_2: world
text_variable_3: foobar

撰写回答