execute python code and save the stdout as a string

Discussion in 'Python' started by jwaixs, Jun 25, 2005.

  1. jwaixs

    jwaixs Guest

    Hello,

    I've a question. Can I execute a part of a python code and put it's
    output in a string? Something like this:

    s = ""
    s = exec """print "Hello World" """
    print s

    Greetz,

    Noud
    jwaixs, Jun 25, 2005
    #1
    1. Advertising

  2. jwaixs wrote:
    > I've a question. Can I execute a part of a python code and put it's
    > output in a string?


    >>> import sys
    >>> from cStringIO import StringIO
    >>>
    >>> def exec_and_get_output(code):

    ... old_stdout = sys.stdout
    ... sys.stdout = StringIO()
    ... try:
    ... exec code in {}, {}
    ... return sys.stdout.getvalue()
    ... finally:
    ... sys.stdout = old_stdout
    ...
    >>> exec_and_get_output("print 'foo'")

    'foo\n'
    Leif K-Brooks, Jun 25, 2005
    #2
    1. Advertising

  3. jwaixs

    jwaixs Guest

    Thank you, this really looks cool!
    jwaixs, Jun 27, 2005
    #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. Elad
    Replies:
    0
    Views:
    401
  2. hycn office
    Replies:
    2
    Views:
    170
    WIlliam Morris
    Oct 10, 2003
  3. Savas Ates
    Replies:
    1
    Views:
    269
    Patrice
    Aug 17, 2004
  4. Andreas S
    Replies:
    3
    Views:
    244
    Eric Hodel
    Dec 9, 2006
  5. Replies:
    2
    Views:
    319
    A. Sinan Unur
    Dec 7, 2005
Loading...

Share This Page