pyyaml

Parse nested custom yaml tags

混江龙づ霸主 提交于 2019-12-23 19:36:55
问题 I have some yaml with application-specific tags (from an AWS Cloud Formation template, to be exact) that looks like this: example_yaml = "Name: !Join [' ', ['EMR', !Ref 'Environment', !Ref 'Purpose']]" I want to parse it so that I can do this: >>> print(result) >>> {'Name': 'EMR {Environment} {Purpose}'} >>> name = result['name'].format( ... Environment='Development', ... Purpose='ETL' ... ) >>> print(name) >>> EMR Development ETL Currently my code looks like this: import yaml from pprint

Parse YAML and assume a certain path is always a string

╄→гoц情女王★ 提交于 2019-12-23 12:25:35
问题 I am using the YAML parser from http://pyyaml.org and I want it to always interpret certain fields as string, but I can't figure out how add_path_resolver() works. For example: The parser assumes that "version" is a float: network: - name: apple - name: orange version: 2.3 site: banana Some files have "version: 2" (which is interpreted as an int) or "version: 2.3 alpha" (which is interpreted as a str). I want them to always be interpreted as a str. It seems that yaml.add_path_resolver()

Load YAML nested with Jinja2 in Python

天大地大妈咪最大 提交于 2019-12-23 09:18:17
问题 I have a YAML file ( all.yaml ) that looks like: ... var1: val1 var2: val2 var3: {{var1}}-{{var2}}.txt ... If I load it in Python like this: import yaml f = open('all.yaml') dataMap = yaml.safe_load(f) f.close() print(dataMap["var3"]) the output is {{var1}}-{{var2}}.txt and not val1-val2.txt . Is it possible to replace the nested vars with the value? I tried to load it with: import jinja2 templateLoader = jinja2.FileSystemLoader( searchpath="/path/to/dir" ) templateEnv = jinja2.Environment(

How to create a datetime object with PyYAML

爱⌒轻易说出口 提交于 2019-12-23 08:29:23
问题 I'd like to be able to create a datetime object with datetime.datetime.now() PyYAML. It's easy to call some functions: >>> y = """#YAML ... description: Something ... ts: !!python/object/apply:time.time []""" >>> yaml.load(y) {'description': 'Something', 'ts': 1289955567.940973} >>> However, I can't seem to figure out how to get a datetime.now() . I've tried as many permutations with calls to that using the various python yaml tags. These all fail: tests = [ 'dt: !!python/object:datetime

Represent instance of different classes with the same base class in pyyaml

蓝咒 提交于 2019-12-22 18:37:45
问题 I have some set of unittests and want to store results of each test run as YAML file for further analysis. Dump data in YAML format fit my needs in several ways. But tests belongs to different suits and results have different parent class, This is example of what I have: >>> rz # shorthand for result [<upstream_suite.fftest.SimpleTest testMethod=test_is_fsType_not_set>, <upstream_suite.openfolder.UfoOpenTest testMethod=test_is_A>, <upstream_suite.openfolder.UfoOpenTest testMethod=test_is_A_a

How to use custom dictionary class while loading yaml?

喜你入骨 提交于 2019-12-22 14:06:00
问题 I am currently loading a YAML file like this import yaml yaml.load('''level0: stuff: string0 level1: stuff: string1 level2: ...''') The code above creates nested dictionaries . Instead of creating nested dictionaries, I want to create nested instances of FancyDict objects. class FancyDict(collections.MutableMapping): def __init__(self, *args, **kwargs): for name in kwargs: setattr(self, name, kwargs[name]) The section on Constructors, Representer, Resolvers doesn't seem to address this case

Can't parse YAML correctly

蹲街弑〆低调 提交于 2019-12-22 10:15:18
问题 I parse the following YAML data in python: >>> import yaml >>> yaml.load(""" ... --- ... categories: {1: Yes, 2: No} ... increasing: [00, 01, 02, 03, 04, 05, 06, 07, 08, 09, 10] ... ... ... """) And get this as output: {'increasing': [0, 1, 2, 3, 4, 5, 6, 7, '08', '09', 10], 'categories': {1: True, 2: False}} Why are "Yes" and "No" converted to True and False? Why are "08" and "09" parsed as strings whereas the other digits are parsed as numbers with leading zeros truncated? 回答1: Your

YAML parsing to Objects (PyYAML Python3)

瘦欲@ 提交于 2019-12-22 08:03:59
问题 I've got the following code: class Settings: def __init__(self, annual_volatility_target): self.annual_volatility_target = annual_volatility_target self.daily = annual_volatility_target/np.sqrt(252) def yaml_load(name): with open('yaml/' + str(name) + '.yaml', 'r') as ymlfile: return yaml.load(ymlfile) settings = yaml_load("settings") With the following YAML: !!python/object:v.Settings annual_volatility_target: 0.25 The problem is, when I load settings , settings.daily isn't set. settings

How to dump YAML with explicit references?

☆樱花仙子☆ 提交于 2019-12-22 06:55:29
问题 Recursive references work great in ruamel.yaml or pyyaml : $ ruamel.yaml.dump(ruamel.yaml.load('&A [ *A ]')) '&id001 - *id001' However it (obviously) does not work on normal references: $ ruamel.yaml.dump(ruamel.yaml.load("foo: &foo { a: 42 }\nbar: { <<: *foo }")) bar: {a: 42} foo: {a: 42} I would like is to explicitly create a reference: data = {} data['foo'] = {'foo': {'a': 42}} data['bar'] = { '<<': data['foo'], 'b': 43 } $ ruamel.yaml.dump(data, magic=True) foo: &foo a: 42 bar: <<: *foo b

How to load a pyYAML file and access it using attributes instead of using the dictionary notation?

不想你离开。 提交于 2019-12-22 06:28:47
问题 I have an YAML config that looks like: config: - id: foo - name: bar content: - run: xxx - remove: yyy I am using Python YAML module to load it but I want to access it in better ways like: stream = open(filename) config = load(stream, Loader=Loader) print(config['content']) What I want is to be able to do: print(config.content) . 回答1: You can use object notation with dictionaries using the following class, as discussed in this answer: class DictAsMember(dict): def __getattr__(self, name):