0

I am running a small client-server test in python and the client sends a word to the server. This word is the name of a function in python it needs to call. So when the word "blink" is sent, it should call the function "blink". (Please not that their could be several keywords and function so it needs to be some form of variable function call).

while True:
    s.listen(1)
    conn, addr = s.accept()
    print 'Connection address:', addr
    while 1:
            data = conn.recv(BUFFER_SIZE)
            if not data: break
            if data == "blink":
                    print "MATCH!"
                    call(data())
            print "received:",data
            call(data())
    print "break"

The word MATCH is printed to clearly the word is received. How to now use the variable data to call the function blink?

I now get

TypeError: 'str' object is not callable

I can understand the error.. clearly I need to do something with that string.. any ideas?

Psidom
  • 209,562
  • 33
  • 339
  • 356
Alex van Es
  • 1,141
  • 2
  • 15
  • 27

1 Answers1

2

You can use dict to map your data to function you want to call.

Functions are first class citizens in Python and can be used like following:

def blink():
    print('Blink')

func = {'blink':blink}
# 'blink' is data you receive;
# blink is the function you want to call
data = 'blink'

func[data]()
Wayne Werner
  • 49,299
  • 29
  • 200
  • 290
galaxyan
  • 5,944
  • 2
  • 19
  • 43
  • 1
    Code-only answers are a bit deprecated; please write why and what you're doing here – Marcus Müller Jul 26 '16 at 18:04
  • Eval worked for me.. but @Morgan Thrapp why not use this? – Alex van Es Jul 26 '16 at 18:10
  • 2
    @AlexvanEs you're commenting at the wrong place. But: Never use `eval()` with external data, for both security reasons, and performance reasons. You don't want **every** python code to be a valid command, but only specific functions. Using `eval` here would be like expecting a parcel, and instead of leaving a note to leave the package, you'd leave your keys, you banking account credentials and birth certificate pinned to the door. – Marcus Müller Jul 26 '16 at 18:13
  • Ok great, thanks for the info! – Alex van Es Jul 26 '16 at 18:14