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?

3
  • 4
    Have a look at this answer. stackoverflow.com/questions/3906232/… It is replacing stdout for the time of execution. Commented Feb 5, 2011 at 0: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? Commented Feb 5, 2011 at 0:12
  • ah i thought of doing something like that then decided it wouldnt work for some reason , but i guess not! Commented Feb 5, 2011 at 0:18

1 Answer 1

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()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.