0
import netifaces
import netaddr
import yaml


class Ethernet(yaml.YAMLObject):
    def __init__(self, addresses, gateway4, mtu, nameservers):
        self.nameservers = nameservers
        self.mtu = mtu
        self.gateway4 = gateway4
        self.addresses = addresses

我正在尝试将此类写入 yum 文件:

with open("/home/netplan.yaml", "w") as file:
    yaml.dump(document, file, default_flow_style=False)

我得到这个结果:

!!python/object:__main__.Netplan
network: !!python/object:__main__.Network
  ethernets:
    docker0: !!python/object:__main__.Ethernet
      addresses:
      - 172.26.0.1/16
      gateway4: 1.1.1.1
      mtu: 9000

如何删除所有元信息,例如 !!python/object: main 来自 yaml 文件?

4

1 回答 1

1

我不知道yum是什么,但我会假设你在谈论 YAML。

您可以定义一个类属性yaml_tag来控制序列化类时使用的标记。如果将其设置为映射的默认标记,则不会写入:

from yaml.resolver import BaseResolver

class Ethernet(yaml.YAMLObject):
    yaml_tag = BaseResolver.DEFAULT_MAPPING_TAG

    def __init__(self, addresses, gateway4, mtu, nameservers):
        self.nameservers = nameservers
        self.mtu = mtu
        self.gateway4 = gateway4
        self.addresses = addresses

但是请注意,如果您这样做,您将无法再次将 YAML 加载到此类中。

如果您无法控制转储的类型,则可以为它们注册一个自定义表示器:

yaml.add_representer(Foo, lambda dumper, data: dumper.represent_mapping(
    BaseResolver.DEFAULT_MAPPING_TAG, data.__dict__))
于 2021-04-23T12:54:34.580 回答