Calling a string as a function.

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Guest's Avatar

    #1

    Calling a string as a function.

    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
    Brandon.mcginty @gmail.com

    --
    No virus found in this outgoing message.
    Checked by AVG Free Edition.
    Version: 7.1.375 / Virus Database: 267.15.0/248 - Release Date: 2/1/2006


  • Grant Edwards

    #2
    Re: Calling a string as a function.

    On 2006-02-03, <brandon.mcgint y@gmail.com> <brandon.mcgint y@gmail.com> wrote:
    [color=blue]
    > How does one go about converting a string, for instants one received through
    > tcp, into something that can be called as a function?[/color]



    Comment

    • Raymond Hettinger

      #3
      Re: Calling a string as a function.

      brandon.mcginty @gmail.com wrote:[color=blue]
      > 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.[/color]

      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

      Comment

      Working...