我们从Python开源项目中,提取了以下6个代码示例,用于说明如何使用ruamel.yaml.safe_dump()。
def save_server(self, server_id, data=None, notes=None): if not data: data = self.data[server_id] if not notes: notes = self.notes[server_id] try: if not os.path.exists("data/{}".format(server_id)): self.add_server(server_id) with open("data/{}/config.yml".format(server_id), "w") as config_fh: yaml.safe_dump(data["config"], config_fh) with open("data/{}/notes.yml".format(server_id), "w") as notes_fh: yaml.safe_dump(self.serialise_notes(notes), notes_fh) with open("data/{}/sections.yml".format(server_id), "w") as sections_fh: yaml.safe_dump(self.serialise_sections(data["sections"]), sections_fh) except Exception: log.exception("Error saving server '{}'".format(server_id))
def get_jinja_env(): env = jinja2.Environment(trim_blocks=True, autoescape=False) env.filters['yaml_safe'] = yaml.safe_dump env.filters['date_time_format'] = date_time_format env.filters['get_date_time_delta'] = get_date_time_delta env.filters['get_date_age'] = get_date_age env.globals['format_resource'] = resource_format env.globals['format_struct'] = format_struct env.globals['get_resource_tag_value'] = get_resource_tag_value env.loader = jinja2.FileSystemLoader( [ os.path.abspath( os.path.join( os.path.dirname(os.path.abspath(__file__)), '..', 'msg-templates')), os.path.abspath('/') ] ) return env
def _write_yaml(self, config_dict, dest): with open(dest, 'w') as f: yaml.safe_dump(config_dict, f, default_flow_style=False)
def merge_definitions(self, defs): compiled_defs = {} for definition in defs: compiled_defs.update(definition.get_parsed_defs()) self.data = yaml.safe_dump(compiled_defs, default_flow_style=False) definitions.data = self.data
def add_server(self, server_id) -> bool: if os.path.exists("data/{}".format(server_id)): return False os.mkdir("data/{}".format(server_id)) with open("data/{}/config.yml".format(server_id), "w") as config_fh: yaml.safe_dump(DEFAULT_CONFIG, config_fh) with open("data/{}/sections.yml".format(server_id), "w") as sections_fh: yaml.safe_dump(DEFAULT_SECTIONS, sections_fh) with open("data/{}/notes.yml".format(server_id), "w") as notes_fh: yaml.safe_dump(DEFAULT_NOTES, notes_fh) self.data[server_id] = { "config": DEFAULT_CONFIG.copy(), "sections": self.load_sections(DEFAULT_SECTIONS) } self.notes[server_id] = DEFAULT_NOTES log.info("Added server: {}".format(server_id)) return True # Convenience functions
def dump_yaml(data, *path): def convert(obj): if isinstance(obj, dict): obj = {k: v for k, v in obj.items() if not k.startswith('_')} return {convert(k): convert(v) for k, v in obj.items()} if isinstance(obj, list): return [convert(x) for x in obj] if isinstance(obj, type): return obj.__name__ return obj filename = os.path.join(*path) ensure_directory(os.path.dirname(filename)) with open(filename, 'w') as file_: yaml.safe_dump(convert(data), file_, default_flow_style=False)