By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
443,814 Members | 1,136 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 443,814 IT Pros & Developers. It's quick & easy.

Executing a script created by the end user

P: n/a
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'
Jul 18 '05 #1
Share this Question
Share on Google+
2 Replies


P: n/a
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
Jul 18 '05 #2

P: n/a
compile and eval is a good way to go.
Regards,

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

Jul 18 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.