Exec Multiple Lines?

C

Chris S.

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.
 
R

Ryan Paul

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")
 
P

Peter Otten

Chris said:
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:
.... print "and I say hello"
.... print "hello, hello"
.... """Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<string>", line 2
print "and I say hello"
^
SyntaxError: invalid syntaxand I say hello
hello, hello
Peter
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top