Question

I have a Python program that takes user input. I store user input a string variable called "userInput". I want to be able to call the string the user entered...

userInput = input("Enter a command: ")
userInput()

From this, I get the error: TypeError: 'str' object is not callable

Currently, I have the program doing something like this:

userInput = input("Enter a command: ")
if userInput == 'example_command':
    example_command()

def example_command():
     print('Hello World!')

Clearly this isn't a very efficient way to process a lot of commands. I want to make the str obj callable - anyway to do so?

Was it helpful?

Solution

A better method might be to use a dict:

def command1():
    pass

def command2():
    pass

commands = {
    'command1': command1,
    'command2': command2
}

user_input = input("Enter a command: ")
if user_input in commands:
    func = commands[user_input]
    func()

    # You could also shorten this to:
    # commands[user_input]()
else:
    print("Command not found.")

Essentially, you're providing a mapping between the literal command, and the function you might want to run.

If that's too much typing, you could also use the local keywords, which will return a dictionary of every function, variable, etc. currently defined within the current scope:

def command1():
    pass

def command2():
    pass

user_input = input("Enter a command: ")
if user_input in locals():
    func = locals()[user_input]
    func()

This isn't entirely secure though, because a malicious user could enter a command which is the same as a variable name, or some function you don't want them to run, and end up crashing your code.

OTHER TIPS

You could do it with the exec method .
Basically the exec command executes strings.

user_input = input()        # example command
exec(user_input + '()')     # append the function parenthesis

You have to keep in mind that it is dangerous to allow users to execute code without proper validation.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top