pypyr.steps.py permalink

run inline python permalink

Executes the context value pycode as python code.

Will execute context['pycode'] as a dynamically interpreted python code block.

For example, this will invoke python print and print 2:

steps:
  - name: pypyr.steps.py
    comment: Example of arb python code. Will print 2.
    in:
      pycode: print(1+1)

working with context permalink

You can access and change the context dictionary in a py step. Changes you make to context will endure after the py step completes.

When you are in a py step, context exists as a dictionary-like object named context. All the usual python dict methods are available.

- name: pypyr.steps.py
  comment: set context value
  in:
    pycode: context['arbkey'] = max(420, 69)
- name: pypyr.steps.py
  comment: get context value
  in:
    pycode: print(context['arbkey'])

multi-line python code block permalink

You can run multiple python statements in the same code block:

- name: pypyr.steps.py
  comment: multi-line statement starts with |, per yaml spec
  in:
    pycode: |
              print(f"py step: {0+1}")
              context['arbvalue'] = 420
              print(context['arbvalue'])              
- name: pypyr.steps.py
  comment: here splitting multi-line statements with ; 
           context['arbvalue'] survives between steps.
  in:
    pycode: print("py step 2"); context['arbvalue'] += 4

Do remember that if your inline code block gets unwieldy, you can very easily run your own Python .py file from pypyr by using it as a custom step in itself.

You don’t even have to package your python code - pypyr will resolve the path relative to the working directory for you.

steps:
  - my-python-file # runs ./my-python-file.py

example permalink

See a worked example of inline python.

see also

last updated on .