470,811 Members | 1,144 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 470,811 developers. It's quick & easy.

Exec Multiple Lines?

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.
Jul 18 '05 #1
2 6377
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")
Jul 18 '05 #2
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.


Either dedent or trick Python into expecting indented code:
s = """ .... print "and I say hello"
.... print "hello, hello"
.... """ exec s Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<string>", line 2
print "and I say hello"
^
SyntaxError: invalid syntax exec "if 1:\n%s" % s and I say hello
hello, hello


Peter

Jul 18 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

5 posts views Thread by PeterF | last post: by
3 posts views Thread by Jerry | last post: by
2 posts views Thread by D. Alvarado | last post: by
3 posts views Thread by John Bowling | last post: by
5 posts views Thread by TPJ | last post: by
31 posts views Thread by eliben | last post: by
7 posts views Thread by gregory.lielens | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.