2

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

def testfunction(function):
    function()

a = raw_input("fill in function name: "
testfunction(a)

So if you fill in an existing function it will execute it.

Henkhooft
  • 21
  • 1
  • 1
  • 2

3 Answers3

4

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".

Blue Peppers
  • 3,718
  • 3
  • 22
  • 24
3

I would probably encapsulate this kind of behavior in a class:

class UserExec(object):
    def __init__(self):
        self.msg = "hello"
    def get_command(self):
        command = str(raw_input("Enter a command: "))
        if not hasattr(self, command):
            print "%s is not a valid command" % command
        else:
            getattr(self, command)()
    def print_msg(self):
        print self.msg
a = UserExec()
a.get_command()

As others have said, this is a security risk, but the more control you have over the input, the less of a risk it is; putting it in a class that includes careful input vetting helps.

senderle
  • 145,869
  • 36
  • 209
  • 233
  • is this procedure version specific? Will Python 3.x look any different? – Arash Howaida Dec 28 '16 at 19:04
  • @ArashHowaida A little different, but it's basic stuff, nothing unexpected or unusual -- in this case just `print` and `raw_input` need changing. I always advise that people familiarize themselves with the difference [here](https://docs.python.org/3/whatsnew/3.0.html). – senderle Dec 28 '16 at 21:25
2

Yes you can, though this is generally a bad idea and a big security risk.

def testfunc(fn):
    fn()

funcname = raw_input('Enter the name of a function')
if callable(globals()[funcname]):
    testfunc(globals()[funcname])
Chinmay Kanchi
  • 62,729
  • 22
  • 87
  • 114