一半君的总结纸

听话只听一半君

如何用pyyaml保存场景dag节点树形结构信息以在maya外查看

话说这个也就用来td支持的时候有意义,至于为什么要用yaml而不是xml呢? 显然xml比ymal快至少10倍,但是….yaml看起来比较酷…

换句话说就是lz想要一个类似outliner的界面,但是是在maya外面的.是用tree结构来存呢,还是用OrderedDict来存,lz还没想好

  • 准备1: 用yaml来保存OrderedDict
    yaml默认存的是dict,所以是不保存顺序的,如果你拿他存python object会有tag,看起来很乱,所以

    #!/usr/bin/env python
    try:
            # for python newer than 2.7
        from collections import OrderedDict
    except ImportError:
            # use backport from pypi
        from ordereddict import OrderedDict
    
    import yaml
    
    # try to use LibYAML bindings if possible
    try:
        from yaml import CLoader as Loader, CDumper as Dumper
    except ImportError:
        from yaml import Loader, Dumper
    from yaml.representer import SafeRepresenter
    _mapping_tag = yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG
    
    
    def dict_representer(dumper, data):
        return dumper.represent_dict(data.iteritems())
    
    
    def dict_constructor(loader, node):
        return OrderedDict(loader.construct_pairs(node))
    
    Dumper.add_representer(OrderedDict, dict_representer)
    Loader.add_constructor(_mapping_tag, dict_constructor)
    
    Dumper.add_representer(str,
                           SafeRepresenter.represent_str)
    
    Dumper.add_representer(unicode,
                           SafeRepresenter.represent_unicode)
    
    
    # output = yaml.dump(data, Dumper=Dumper, default_flow_style=False)
    
    # data = yaml.load(stream, Loader=Loader)
    # abc:
    #   x:
    #     0: null
    #   y:
    #     1: null
    yml_dict = OrderedDict(
        abc=OrderedDict(
            [('x', OrderedDict([(0, None)])), ('y', OrderedDict([(1, None)]))]))
    
    import json
    print(json.dumps(yml_dict, indent=2))
    print
    
    # dump ordereddict to yaml
    output = yaml.dump(yml_dict, Dumper=Dumper, default_flow_style=False)
    print output
    
    # directly write to a file object to save memory.
    with open('result.yml', 'w') as f:
        yaml.dump(yml_dict, f, default_flow_style=False)
    

    但是上面的方法不好,如果是在maya里用的工具,会导致ymal module永久的被改变,除非重启maya,最好subclass Resolver 和 Loader 还有Dumper,如果是在外面运行而且不会被别人import的话就无所谓

参考:
In Python, how can you load YAML mappings as OrderedDicts?
Constructors, representers, resolvers – PyYAML Documentation
pyyaml: dumping without tags

Advertisements

发表评论

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / 更改 )

Twitter picture

You are commenting using your Twitter account. Log Out / 更改 )

Facebook photo

You are commenting using your Facebook account. Log Out / 更改 )

Google+ photo

You are commenting using your Google+ account. Log Out / 更改 )

Connecting to %s

%d 博主赞过: