Exec Multiple Lines?

Discussion in 'Python' started by Chris S., Jun 12, 2004.

  1. Chris S.

    Chris S. Guest

    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.
    Chris S., Jun 12, 2004
    #1
    1. Advertising

  2. Chris S.

    Ryan Paul Guest

    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")
    Ryan Paul, Jun 12, 2004
    #2
    1. Advertising

  3. Chris S.

    Peter Otten Guest

    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
    Peter Otten, Jun 12, 2004
    #3
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Hal Vaughan
    Replies:
    11
    Views:
    1,085
    Gordon Beaton
    May 22, 2006
  2. tedsuzman
    Replies:
    2
    Views:
    7,057
    Michel Claveau, résurectionné d'outre-bombe inform
    Jul 21, 2004
  3. Ted
    Replies:
    1
    Views:
    448
    Duncan Booth
    Jul 22, 2004
  4. Guillermo Riojas
    Replies:
    0
    Views:
    155
    Guillermo Riojas
    Nov 26, 2010
  5. Cah Sableng
    Replies:
    0
    Views:
    230
    Cah Sableng
    Apr 23, 2007
Loading...

Share This Page