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

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

  3. jwaixs

    jwaixs Guest

    Thank you, this really looks cool!
     
    jwaixs, Jun 27, 2005
    #3
    1. Advertisements

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. nick
    Replies:
    2
    Views:
    477
    Rick Strahl [MVP]
    Dec 24, 2003
  2. Andy

    Execute c# code from a string?

    Andy, May 18, 2004, in forum: ASP .Net
    Replies:
    2
    Views:
    14,596
    Scott Allen
    May 18, 2004
  3. Jeff Learman

    shell script stdout to python string?

    Jeff Learman, May 20, 2004, in forum: Python
    Replies:
    2
    Views:
    1,464
    Jeff Learman
    May 20, 2004
  4. Elad
    Replies:
    0
    Views:
    591
  5. hycn office
    Replies:
    2
    Views:
    324
    WIlliam Morris
    Oct 10, 2003
  6. Savas Ates
    Replies:
    1
    Views:
    464
    Patrice
    Aug 17, 2004
  7. Andreas S
    Replies:
    3
    Views:
    468
    Eric Hodel
    Dec 9, 2006
  8. Replies:
    2
    Views:
    610
    A. Sinan Unur
    Dec 7, 2005
Loading...