Executing a script created by the end user
Steven Bethard
steven.bethard at gmail.com
Sun Jan 16 16:08:38 EST 2005
Craig Howard wrote:
> 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'
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
More information about the Python-list
mailing list