By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
438,427 Members | 1,356 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 438,427 IT Pros & Developers. It's quick & easy.

execute python code and save the stdout as a string

P: n/a
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

Jul 19 '05 #1
Share this Question
Share on Google+
2 Replies


P: n/a
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'
Jul 19 '05 #2

P: n/a
Thank you, this really looks cool!

Jul 19 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.