Reputation: 11
I'm trying to make a command prompt style program in Python. I want to have a list of possible functions to run, and then check the list; if any of them match, take the input that matched and call a function with the same name. I currently get a "str" object is not callable
error.
import os
import time
able_commands = ["clear", "test"]
def test():
print("worked")
def run_command(command):
command()
input_command()
def clear():
print("clearing...")
time.sleep(2)
os.system('cls')
def input_command():
command = input(os.path.abspath(os.sep) + " ")
check_if = command.lower()
if check_if in able_commands:
run_command(check_if)
elif check_if == "":
input_command()
else:
print("ERROR \nPlease specify a valid command")
input_command()
input_command()
I'm a beginner with Python.
Upvotes: 0
Views: 168
Reputation: 29
In Python, functions are first-class objects. So, you could do something like this:
def foo():
print('foo')
def bar():
print('bar')
# Create a dict of function name to the function object.
# This dict must be declared after your functions otherwise
# you will get a NameError exception.
funcs = {
'run_foo': foo
'run_bar': bar
}
# Select the function from the dict
f = funcs['run_foo']
# Run the selected function
f()
Upvotes: 1
Reputation: 1556
In python, you can call functions like this using globals() and locals(). In your case, you can replace line command()
inside def run_command(command)
with this:
globals()[command]()
This will find your function by name and call it. Be careful when using globals though, and please also read this SO post. You will find more ways of calling your function and explanations there. I hope, this helps.
Upvotes: 0
Reputation: 68
A simple implementation of what you require is to change your run_command
function to the following:
def run_command(command):
functionToCall = globals()[command]
functionToCall()
input_command()
There are similar questions already that answer this, however for a "newbie", it may not be clear that they in fact are the same, or how they'd fit into your implementation.
Upvotes: 0