Exec Multiple Lines?

Ryan Paul segphault at sbcglobal.net
Sat Jun 12 02:53:51 EDT 2004


On Sat, 12 Jun 2004 02:26:39 -0400, Chris S. wrote:

> I'd like to dynamically execute multiple lines of indented code from 
> within a script, but I can't seem to find a suitable function. Exec only 
> works with unindented code, and execfile only works with files. I 
> suppose I could write my string to a temporary file and then use 
> execfile, but that seems like a hack. Is there an easier way? Any help 
> is appreciated.

txt = """
class myclass:
  def testf(s,x,y):
    print "testf called with %s,%s"%(x,y)
"""

exec(compile(txt,"-","exec"))

a = myclass()
a.testf("var1","var2")



More information about the Python-list mailing list