pypyr.parser.keyvaluepairs permalink

pass key-value pairs from cli to pipeline permalink

Takes key=value pairs from cli arg input and initialize context with a dictionary where each pair becomes a dictionary element.

term
$ pypyr my-pipeline key1=value1 key2=2 key3="value 3"
_

This will parse to context like this:

{
  'key1': 'value1',
  'key2': '2',
  'key3': 'value 3'
  }

Escape literal spaces with single or double quotes.

Any arg without an = will parse to key: ''.

term
$ pypyr my-pipeline arg0 key1=value1 key2=2 key3="value 3"
_

This will parse to context like this:

{
  'arg0': '',
  'key1': 'value1',
  'key2': '2',
  'key3': 'value 3'
  }

special characters permalink

Notice that you can have both keys and values with spaces by using either single or double quotes. If you need to escape quotes, refer to your shell’s documentation for escape characters.

term
$ pypyr my-pipeline param1=value1 param2='value 2' "param 3"=123
{'param1': 'value1', 'param2': 'value 2', 'param 3': '123'}

Although you can have spaces and special characters such as punctuation in your keys (such as “param 3” above), for an easy life you might want to avoid doing so.

The reason is that when you want to reference your context keys in {formatting expressions} or variables in py string expressions or in a pypyr.steps.py step you’re going to run into trouble - so it’s best to stick to keys that are valid Python identifiers.

Simply put, don’t have punctuation other than _ in your keys unless you’re really sure you’re willing to live with the side-effects.

While you might want to keep your keys as free of special characters as you can, the values can be whatever you want:

term
$ pypyr my-pipeline key1='value !@£$%^&' key_2=nothing_special
_

Will initialize context like this:

{
  'key1': 'value !@£$%^&',
  'key_2': 'nothing_special'
}

When parsing key=value pairs, pypyr only considers the first = as marking the key, subsequent = in the same arg will be considered part of the value:

term
$ pypyr my-pipeline k1=one+two=three k2=arb
_

Will result in:

{
  'k1': 'one+two=three',
  'k2': 'arb'
}

example permalink

Given a pipeline like this, arbitrarily saved as ./keyvaluepairs-parser.yaml:

# ./keyvaluepairs-parser.yaml
context_parser: pypyr.parser.keyvaluepairs
steps:
  - pypyr.steps.debug # prints at log level <=20

You can then pass key-value pairs from the cli to the pipeline to initialize context. Notice that you can have both keys and values with spaces by using either single or double quotes.

term
$ pypyr keyvaluepairs-parser param1=value1 param2='value 2' "param 3"=123 --log 20
{'param1': 'value1', 'param2': 'value 2', 'param 3': '123'}

see also

last updated on .