使用 ruamel.yaml 读写 yaml 文档,解决16进制混搭10进制数据读出来全是10进制
import ruamel.yaml class LaoLiuNiuBiVersionedResolver(ruamel.yaml.SafeLoader): def __init__(self, *args, **kwargs): super(LaoLiuNiuBiVersionedResolver, self).__init__(*args, **kwargs) self.yaml_constructors['tag:yaml.org,2002:hex'] = self.parser_hex def parser_hex(self, _, node): return node.value def resolve(self, kind, value, implicit): if value and value.startswith('0x'): return 'tag:yaml.org,2002:hex' else: return super(LaoLiuNiuBiVersionedResolver, self).resolve(kind, value, implicit) data = ruamel.yaml.load(""" x: 42 a: 0x2a z: 0o52 """, Loader=LaoLiuNiuBiVersionedResolver) print(data, )
写入的时候十六进制被转成了字符串,但是那个不能是字符串:
ruamel这个模块,你用round_trip_load取出来的时候,你16进制的数据,其实显示出来是10进制,但是你保存的时候又是16进制的,因为它内部做了一个转换
,自定义的类型叫HexInt,用这个类型保存16进制的,再写入进去的时候就可以完美解决了,不用做任何转换。
import ruamel.yaml from ruamel import yaml import sys import json from ruamel.yaml.scalarint import ScalarInt, BinaryInt, OctalInt, HexInt, HexCapsInt with open('faucet.yaml',"r") as f: a = yaml.round_trip_load(f) f.close() a["acls"]["system"][0]["rule"]["eth_type"] = HexInt(100) with open('faucet.yaml', 'w') as nf: yaml.round_trip_dump(a, nf, Dumper=yaml.RoundTripDumper) nf.close() # print(HexInt(300),type(HexInt(300)))
每天逼着自己写点东西,终有一天会为自己的变化感动的。这是一个潜移默化的过程,每天坚持编编故事,自己不知不觉就会拥有故事人物的特质的。 Explicit is better than implicit.(清楚优于含糊)