Exec Multiple Lines?

Peter Otten __peter__ at web.de
Sat Jun 12 10:01:31 CEST 2004


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




More information about the Python-list mailing list