Home > front end >  How to execute a function stored in a dictionary with the interaction of a user in Python?
How to execute a function stored in a dictionary with the interaction of a user in Python?

Time:09-27

I code a small personal project. Is it possible to call a function with input from a user? Let me explain. If for example the user marks "help", I would like the "cmdHelp ()" function to run. I would like to use a dictionary to be able to do this more cleanly, and store my functions.

def userInput():
    RUN = 1
    while(RUN != 0):
        USER = input('↪ ').lower()
        if USER in cmd:
            #execute the function

def helpCmd():
    print('THIS IS THE HELP MENU AHAHAHA !')

def connexion():
    print("› SSH\n› FTP\n")

cmd = {
   'help': helpCmd,
   'connexion': connexion
}

CodePudding user response:

Yes, that's fine, just access the dict and call the returned function:

def userInput():
    RUN = 1
    while(RUN != 0):
        USER = input('↪ ').lower()
        if USER in cmd:
            cmd[USER]()

To be clear, there are two steps here:

func = cmd[USER]  # Access cmd to find the function
func()            # now call the function

CodePudding user response:

The below is the way to go: (Note that code print an error message in case of a wrong input)

def userInput():
    RUN = 1
    while(RUN != 0):
        cmd_key = input('↪ ').lower()
        func = cmd_lookup.get(cmd_key)
        if func is not None:
            func()
        else:
            print(f'{cmd_key} is invliad func name. Available names are: {[c for c in cmd_lookup.keys()]}')



def helpCmd():
    print('THIS IS THE HELP MENU AHAHAHA !')

def connexion():
    print("› SSH\n› FTP\n")

cmd_lookup = {
   'help': helpCmd,
   'connexion': connexion
}

userInput()

CodePudding user response:

Unrelated to the question, some edits to fit pep-8 rules:

1: use run instead of RUN, so with user not USER.

2: use while run instead of while (run != 0).

3: name your function user_input instead of userInput and so as help_cmd.

4: if you never change cmd dynamically, i.e you don't modify it - add/remove items from it, then you better name it CMD. objects which are "constants" can be named with capital letters.

  • Related