Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using user input to call functions

Tags:

python

I was trying to make a "game" in Python where the user inputs a command. However, I do not know whether you can take that input to be a function name. This is my current effort:

def move():
    print("Test.")

if __name__ == "__main__":
    input("Press enter to begin.")
    currentEnvironment = getNewEnvironment(environments)
    currentTimeOfDay = getTime(timeTicks, timeOfDay)
    print("You are standing in the {0}. It is {1}.".format(currentEnvironment, currentTimeOfDay))
    command = input("> ")
    command()

Here, the input was move, as I wanted to try and call that function (as a potential end user might). However, I get the following error:

Traceback (most recent call last):
  File "D:\Text Adventure.py", line 64, in <module>
    command()
TypeError: 'str' object is not callable

I was wondering if there was any way that I could allow a user to 'move' in the game, which the program achieves by calling the "move" function.

like image 385
Jon Avatar asked Nov 30 '25 15:11

Jon


2 Answers

It looks like you're using python3.x where input returns a string. To recover the python2.x behavior, you need eval(input()). However, you shouldn't do this. It's likely to lead to a bad day.


A better idea is to put the functions into a dictionary --

def move():
    #...

def jump():
    #...

function_dict = {'move':move, 'jump':jump }

and then:

func = input('>')  #raw_input on python2.x
function_dict[func]()

The following code works for me on python3.2.

def move():
    print("Test.")

func_dict = {'move':move}
if __name__ == "__main__":
    input("Press enter to begin.")
    currentEnvironment = "room" #getNewEnvironment(environments)
    currentTimeOfDay = "1 A.M." #getTime(timeTicks, timeOfDay)
    print("You are standing in the {0}. It is {1}.".format(currentEnvironment, currentTimeOfDay))
    command = input("> ")
    func_dict[command]()
like image 133
mgilson Avatar answered Dec 03 '25 06:12

mgilson


You can access functions by name using:

function = globals()[function_name]

if the function is in the current module, or

function = getattr(other_module, function_name)

You should also take measures to disallow calling arbitrary functions, for example, prefixing:

 def cmd_move() # ok to call this
 def cmd_jump() # ok to call this

 def internal_func....

 cmd = raw_input('>') # e.g. "move"
 fun = globals()['cmd_' + cmd]
 fun()
like image 31
georg Avatar answered Dec 03 '25 05:12

georg



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!