Executing a script created by the end user

Nick Coghlan ncoghlan at iinet.net.au
Mon Jan 17 05:27:47 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

Take a look at the execfile builtin.

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

Alternatively:

Py> exec """
... def main():
...     hello1()
...     hello2()
...
... def hello1():
...     print 'hello1'
...
... def hello2():
...     print 'hello2'
... """
Py> main()
hello1
hello2

'exec' is quite happy to deal with newlines and indenting.

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at email.com   |   Brisbane, Australia
---------------------------------------------------------------
             http://boredomandlaziness.skystorm.net



More information about the Python-list mailing list