Storing and reusing values from Python code

The state variable can store and retain a single value while the project is running, but if you want to store multiple values persistently, you will need to pass them from the Python code inside the Live Python block to generic controls. The values can then be passed back to the Python code when they are needed.

Notes:

To store and reuse values from Python code

  1. Add a NION to the design page.
  2. Add a Live Python block to the design page with six inputs.
  3. Add four buttons to the design page, then wire them to the first four inputs on the Live Python block.
  4. Label the buttons as follows:
  5. Add two string controls (Value 1 and Value 2) to the design page, then add both master and slave wiring nodes to them.
  6. Wire both the master and slave nodes on the first string control to the fifth input wiring node on the Live Python block.
  7. Wire both the master and slave nodes on the second string control to the last input wiring node on the Live Python block.

  8. Emulate the project.
  9. Double-click the Live Python block to open it.
  10. Double-click the Edit button to open the Python source code editor.
  11. Type the code below into the editor and then save the file.

    total=0

    # Save value 1 button as a string

    if inputs[0].changed_get():

      inputs[4].string_set("25")

    # Save value 2 button as a string

    if inputs[1].changed_get():

      inputs[5].string_set("50")

    # Show add integer values of saved strings and display

    if inputs[2].changed_get():

      total = int(inputs[4].string_get()) + int(inputs[5].string_get())

      message.string_set(total)

    # Reset displayed values

    if inputs[3].changed_get():

      inputs[4].string_set("")

      inputs[5].string_set("")

      message.string_set("")

  12. Click the Save value 1 button.
  13. The value 25 is saved in the first string control.
  14. Click the Save value 2 button.

    The value 50 is saved in the second string control.

  15. Click the Show final total button.

    The final value 75 is calculated using the saved values, then it is displayed on the control surface of the Live Python block.

    If you want to run the sequence again, click the Reset button, and refer to step 12.

See also

Controlling the execution of Python code

Using the state variable to store a value persistently

Using threading to run scripts autonomously