Reputation: 905
I want to create some kind of user interface and the user should be able to type the name of the function he wishes to run:
task = input('Programm to run: ')
Once task
is defined I want to execute the desired task like:
task()
If for example the desired program is functon
the script shall execute function()
.
Upvotes: 0
Views: 153
Reputation: 23
Like said in the comments, you can create a dictionary and run the functions from it:
def func1(): print('I am f1')
def func2(): print('I am f2')
def func3(): print('I am f3')
functions = {'f1': func1, 'f2': func2, 'f3': func3}
x = input('which function:')
functions[x]() # call the function
Upvotes: 1
Reputation: 21
Here is another way for doing it globally:
def foo():
print("foo")
def bar():
print("bar")
method = input("What method: ") # ask for method
globals().get(method, lambda: 0)() # search for global method and execute it
Upvotes: 1
Reputation: 36033
Here's one way:
class Tasks(object):
def foo(self):
print('hi')
def bar(self):
print('bye')
task = 'foo'
getattr(Tasks(), task)()
Upvotes: 0