Executing a script created by the end user

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Craig Howard

    #1

    Executing a script created by the end user

    I am working on a python project where an object will have a script that
    can be edited by the end user: object.script

    If the script is a simple one with no functions, I can easily execute it
    using:
    exec object.script

    But if the object script is a bit more complicated, such as the example
    below, my approach does not work:

    def main():
    hello1()
    hello2()

    def hello1():
    print 'hello1'

    def hello2():
    print 'hello2'
  • Steven Bethard

    #2
    Re: Executing a script created by the end user

    Craig Howard wrote:[color=blue]
    > I am working on a python project where an object will have a script that
    > can be edited by the end user: object.script
    >
    > If the script is a simple one with no functions, I can easily execute it
    > using:
    > exec object.script
    >
    > But if the object script is a bit more complicated, such as the example
    > below, my approach does not work:
    >
    > def main():
    > hello1()
    > hello2()
    >
    > def hello1():
    > print 'hello1'
    >
    > def hello2():
    > print 'hello2'[/color]

    What do you want to do if you get a script like this? Run main? You
    could do something like:

    py> s = """
    .... def main():
    .... hello1()
    .... hello2()
    ....
    .... def hello1():
    .... print 'hello1'
    ....
    .... def hello2():
    .... print 'hello2'
    .... """
    py> d = {}
    py> exec s in d
    py> d["main"]()
    hello1
    hello2

    (Actually, you don't need to exec it in d, that's probably just good
    practice.)

    Steve

    Comment

    • Fuzzyman

      #3
      Re: Executing a script created by the end user

      compile and eval is a good way to go.
      Regards,

      Fuzzy
      http://www.voidspace.org.uk/python/index.shtml

      Comment

      Working...