Сброс коллекции в файл YAML с помощью PyYaml - PullRequest
0 голосов
/ 13 июля 2010

Я пишу приложение на Python.Я пытаюсь выгрузить свой объект python в yaml, используя PyYaml.Я использую Python 2.6 и запускаю Ubuntu Lucid 10.04.Я использую пакет PyYAML в пакете Ubuntu: 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.

Я использую следующий API pyYaml для выгрузки экземпляра 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 {valid_action: true, описание: My Configuration, включено: true, рекурсивно: true, source_folder: source_folder} rule_verb: !! python / object: Miranda.RuleVerb {сжатие: true, dest_folder: / home / zainul / Downloads, тип: Move File} * * тысяча двадцать-один

1 Ответ

2 голосов
/ 13 июля 2010

Модуль 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
...