我正在编写一个python应用程序。我试图使用PyYaml将我的python对象转储到yaml中。我正在使用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');
这是输出:
!!蟒/对象:Miranda.Rule rule_condition:ALL rule_setting:!! python / object:Miranda.RuleSetting {confirm_action:true,description:My 配置,启用:true,递归:true,source_folder:source_folder} rule_verb:!! python / object:Miranda.RuleVerb {compression:true,dest_folder:/ home / zainul / Downloads, 类型:移动文件}
答案 0 :(得分: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