Python call function from user input

前端 未结 3 1653
长发绾君心
长发绾君心 2021-01-03 13:40

Can you call functions from user input? Something like this:

def testfunction(function):
    function()

a = raw_input(\"fill in function name: \"
testfuncti         


        
3条回答
  •  执念已碎
    2021-01-03 14:16

    What you are doing is bad bad bad :P However, it's perfectly possible.

    a = raw_input("Fill in function name:")
    if a in locals().keys() and callable(locals()['a']):
        locals()['a']()
    else:
        print 'Function not found'
    

    locals() returns a dictionary of all the objects currently avalible, and their names. So when we say a in locals().keys() we are saying, "Is there any object called ". If there is, we then get it by doing locals()['a'] and then test if it is a function using callable. If that is True aswell, then we call the function. If it is not, we simply print "Function not found".

提交回复
热议问题