PyYAML转储没有标签的Python对象

时间:2018-02-15 17:55:27

标签: python-3.x pyyaml

如何使用PyYAML转储没有标签的Python对象? 我有这样的课程:

class Monster(yaml.YAMLObject):
    yaml_tag = u'!Monster'
    def __init__(self, name, hp, ac, attacks):
        self.name = name
        self.hp = hp
        self.ac = ac
        self.attacks = attacks

然后我尝试转储:

print(yaml.dump(Monster(name='Cave lizard', hp=[3,6], ac=16, attacks=['BITE','HURT'])))

得到了结果:

!Monster
ac: 16
attacks: [BITE, HURT]
hp: [3, 6]
name: Cave lizard

但理想的结果是:

ac: 16
attacks: [BITE, HURT]
hp: [3, 6]
name: Cave lizard

我怎么能得到这个?

1 个答案:

答案 0 :(得分:4)

由于您不想发出标记,因此应将执行此操作的方法更改为无操作:

import yaml
import sys

class Monster(yaml.YAMLObject):
    yaml_tag = u'!Monster'
    def __init__(self, name, hp, ac, attacks):
        self.name = name
        self.hp = hp
        self.ac = ac
        self.attacks = attacks

def noop(self, *args, **kw):
    pass

yaml.emitter.Emitter.process_tag = noop

yaml.dump([
    Monster(name='Cave lizard', hp=[3,6], ac=16, attacks=['BITE','HURT']),
    Monster(name='Sméagol', hp=400, ac=14, attacks=['TOUCH','EAT-GOLD']),
], sys.stdout, allow_unicode=True)

给出:

- ac: 16
  attacks: [BITE, HURT]
  hp: [3, 6]
  name: Cave lizard
- ac: 14
  attacks: [TOUCH, EAT-GOLD]
  hp: 400
  name: Sméagol

请注意,使用print(yaml.dump())在时间和内存方面效率低下。 PyYAML有一个流接口,所以你应该直接使用它而不是流式传输到缓冲区,然后使用print()

流式传输缓冲区