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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With