execute python code and save the stdout as a string

Leif K-Brooks eurleif at ecritters.biz
Sat Jun 25 09:18:27 EDT 2005


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'



More information about the Python-list mailing list