'Python3 console-menu library, carry-over information

I've had a need to quickly activate some relays on my microcontroller for testing, that does not involve a complicated matter. I've found "console-menu" and it looks and works great for my purpose.

After installing and looking at the information and examples, I had the idea to list up my relays, and switch their states between an "on" and and "off". As some microcontrollers have more than 20 relays, I have come up with the following code:

import sys

from consolemenu import *
from consolemenu.items import *


def action(state):
    pu = PromptUtils(Screen())
    pu.println("\nState switched to:", state, "\n")
    pu.enter_to_continue()

def main():
    menu = ConsoleMenu("Relay Menu", "This is the Relay Selection Menu")

    # Create a second submenu, but this time use a standard ConsoleMenu instance
    submenu = ConsoleMenu("State", "Please select your desired state.")
    function_item_1 = FunctionItem("Relay ON", action, args=['ON'])
    function_item_2 = FunctionItem("Relay OFF", action, args=['OFF'])
    submenu.append_item(function_item_1)
    submenu.append_item(function_item_2)
    submenu_item_1 = SubmenuItem("Relay 1", submenu=submenu)
    submenu_item_1.set_menu(menu)
    submenu_item_2 = SubmenuItem("Relay 2", submenu=submenu)
    submenu_item_2.set_menu(menu)

    # Add all the items to the root menu
    menu.append_item(submenu_item_1)
    menu.append_item(submenu_item_2)

    # Show the menu
    menu.start()
    menu.join()


if __name__ == "__main__":
    main()

I am able to further build this out to as many relays as I want, and am able to switch their state from a simple sub-menu that applies to all relays.

The issue I've run against is that I'm unable to carry forward the information which relay and state is selected.

I've looked a the documentation and the classes files, and was able to find:

def get_submenu(self):
    """
    We unwrap the submenu variable in case it is a reference to a method that returns a submenu
    """
    return self.submenu if not callable(self.submenu) else self.submenu()

And I believe this I can use to catch the variable and pass it on so that I know which submenu was selected, although I have no idea how it works I have tried to read up on this.

I don't need a finished answer, as I'd like to learn - a nudge in the right direction would be really helpful!



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source