pypyr.parser.yamlfile permalink

read yaml file into context permalink

Opens a yaml file from the input path and use it to initialize the pypyr context dictionary. Strongly typed values in the source yaml will translate into the pipeline context with the correct type. This lets you initialize pipeline context from a yaml file.

The input path can be relative or absolute. Relative paths are relative to the current working directory.

example permalink

Given a yaml file like this, saved as ./sample-files/sample.yaml:

key1: value1
key2: value 2
key3: "value3 and {key1} and {key2}"
echoMe: "this is a value from a yaml file"
keyInt: 123
keyBool: True

And given a pipeline like this, arbitrarily saved as ./yamlfile-parser.yaml:

# ./yamlfile-parser.yaml
context_parser: pypyr.parser.yamlfile
steps:
  # echoMe is set in the yaml file
  - pypyr.steps.echo
  - name: pypyr.steps.set
    comment: use the int as a strongly typed int
    in:
      set:
        intResult: !py keyInt * 2
  
  - name: pypyr.steps.echo
    comment: formatting expressions in yaml file will work
    in:
      echoMe: '{key3}'
  
  - name: pypyr.steps.echo
    comment: print out result of int calculation
    in:
      echoMe: "strongly typed happens automatically: {intResult}"
  
  - name: pypyr.steps.echo
    comment: only run if input bool is true
    run: '{keyBool}'
    in:
      echoMe: you'll only see me if the bool was true

You can run this pipeline as follows:

$ pypyr yamlfile-parser ./sample-files/sample.yaml
this is a value from a yaml file
value3 and value1 and value 2
strongly typed happens automatically: 246
you'll only see me if the bool was true

If you change the keyBool bool to False:

$ pypyr yamlfile-parser ./sample-files/sample.yaml
this is a value from a yaml file
value3 and value1 and value 2
strongly typed happens automatically: 246

yaml structure permalink

The top (or root) level yaml should describe a map, not a sequence.

Sequence (this won’t work):

- thing1
- thing2

Instead, do a map (aka dictionary):

thing1: thing1value
thing2: thing2value

spaces in file path permalink

Depending on your O/S, shell and file-system, it’s up to you to deal with special characters in the file-name.

Taking MacOS as an example, all of the following will work:

$ pypyr mypipeline ./testfiles/sample.yaml
$ pypyr mypipeline ./test files/sample with space.yaml
$ pypyr mypipeline "./test files/sample with space.yaml"
$ pypyr mypipeline ./"test files"/"sample with space.yaml"

encoding permalink

By default the yaml file will read in the platform’s default encoding. This is utf-8 for most systems, but be aware on Windows it’s still cp1252.

See here for more details on handling text encoding in pypyr and changing the defaults.

see also

last updated on .