Calling a string as a function.

G

Guest

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.
Thanks Much,
Brandon McGinty
(e-mail address removed)
 
R

Raymond Hettinger

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() # lookup the string and run it if defined
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,283
Messages
2,571,405
Members
48,100
Latest member
Calfin5299

Latest Threads

Top