Python中的Yaml合并

Yaml merge in Python(Python中的Yaml合并)
本文介绍了Python中的Yaml合并的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

所以我正在玩弄让自己(当然还有任何关心使用它的人)在 Python 中为 Pygame 制作一个小样板库的想法.我想要一个系统,其中应用程序的设置随 yaml 文件一起提供.

So I'm toying around with the idea of making myself (and anyone who cares to use it of course) a little boilerplate library in Python for Pygame. I would like a system where settings for the application are provided with a yaml file.

所以我想如果库提供一个默认的 yaml 树并将它与用户提供的树合并它会很有用.出于可用性考虑,我想知道是否有任何人可以预测一个例程:

So I was thinking it would be useful if the library provided a default yaml tree and merged it with a user supplied one. For usability sake I wonder if possible there are any out there who can divine a routine where:

在树中用户提供的 yaml 与默认值重叠的任何情况下,用户提供的分支都会替换库提供的分支.

In any case in the tree where the user supplied yaml overlaps the default, the user supplied branches replace the library supplied ones.

在用户提供的 yaml 不与默认树重叠的任何情况下,默认树仍然存在.

In any case where the user supplied yaml does not overlap the default tree, the default tree persists.

用户提供的 yaml 提供的树中的任何多余分支都会被附加.

Any superflous branches in the tree provided by the user supplied yaml are appended.

我知道这个解释很冗长,因为我的要求可能很清楚.我想知道免费获得是不是有点多.

I know this explanation was verbose as it is probably clear what I'm asking for. I wonder if it is a bit much to get for free.

推荐答案

你可以使用 PyYAML 来解析文件,然后使用以下函数合并两棵树:

You could use PyYAML for parsing the files, and then the following function to merge two trees:

def merge(user, default):
    if isinstance(user,dict) and isinstance(default,dict):
        for k,v in default.iteritems():
            if k not in user:
                user[k] = v
            else:
                user[k] = merge(user[k],v)
    return user

或者,您可以在调用之前对用户树进行 deep-copy这个函数.

Optionally, you could do a deep-copy of the user-tree before calling this function.

这篇关于Python中的Yaml合并的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

How do I make a list of all members in a discord server using discord.py?(如何使用 discord.py 列出不和谐服务器中的所有成员?)
how to change discord.py bot activity(如何更改 discord.py 机器人活动)
Issues with getting VoiceChannel.members and Guild.members to return a full list(让 VoiceChannel.members 和 Guild.members 返回完整列表的问题)
Add button components to a message (discord.py)(将按钮组件添加到消息(discord.py))
on_message() and @bot.command issue(on_message() 和@bot.command 问题)
How to edit a message in discord.py(如何在 discord.py 中编辑消息)