Calling a string as a function.
Raymond Hettinger
python at rcn.com
Fri Feb 3 00:34:10 EST 2006
brandon.mcginty at gmail.com wrote:
> I'm completely new to python, so sorry for my ignorence.
> How does one go about converting a string, for instants one received through
> tcp, into something that can be called as a function?
> I'm trying to have what the user sends to the computer through the network,
> run as a function.
> If the user sends "motd", the function motd will be run inside the script.
The unsafe way is to run the string through exec or eval():
s = 'motd()' # string received from user via the network
. . .
exec s
A safer way is to create a limited vocabulary of calls,
look them up in a dictionary and dispatch them to pre-built functions:
vocab = {'motd': motd, 'quit':quit, 'save':save}
. . .
s = 'motd' # string received from user via the network
. . .
vocab[s]() # lookup the string and run it if defined
More information about the Python-list
mailing list