9

What's a good way to exec a bunch of python code, like exec mycode, and capture everything it prints to stdout into a string?

Claudiu
  • 224,032
  • 165
  • 485
  • 680
  • 4
    Have a look at this answer. http://stackoverflow.com/questions/3906232/python-get-the-print-output-in-an-exec-statement/3906390#3906390 It is replacing stdout for the time of execution. – Reiner Gerecke Feb 05 '11 at 00:06
  • @Reiner: Although this question is worded better, it's basically a dup of that one (and that one has a fantastic answer!). Should this be closed & pointed to that one? – Gerrat Feb 05 '11 at 00:12
  • ah i thought of doing something like that then decided it wouldnt work for some reason , but i guess not! – Claudiu Feb 05 '11 at 00:18

1 Answers1

11

Try replacing the default sys.stdout, like in this snippet:

import sys
from StringIO import StringIO

buffer = StringIO()
sys.stdout = buffer

exec "print 'Hello, World!'"

#remember to restore the original stdout!
sys.stdout = sys.__stdout__

print buffer.getvalue()
vrde
  • 937
  • 1
  • 11
  • 25