Skip to main content
AI Assist is now on Stack Overflow. Start a chat to get instant answers from across the network. Sign up to save and share your chats.

You are not logged in. Your edit will be placed in a queue until it is peer reviewed.

We welcome edits that make the post easier to understand and more valuable for readers. Because community members review edits, please try to make the post substantially better than how you found it, for example, by fixing grammar or adding additional resources and hyperlinks.

5
  • Love this solution. I modified, so as not to accidentally lose stuff from a stream on which I'm not expecting output, e.g. unexpected errors. In my case, capture() can accept sys.stderr or sys.stdout as a parameter, indicating to only capture that stream. Commented May 2, 2013 at 23:00
  • StringIO doesn't support unicode in any fashion, so you can integrate the answer here to make the above support non-ASCII chars: stackoverflow.com/a/1819009/425050 Commented Sep 10, 2013 at 7:59
  • 4
    Modifying a yielded value in the finally is really rather wierd - with capture() as out: will behave differently to with capture() as out, err: Commented Sep 17, 2013 at 8:29
  • 2
    Unicode / stdout.buffer support can be reached with using the io module. See my answer. Commented Oct 13, 2013 at 11:55
  • 3
    This solution breaks if you use subprocess and redirect output to sys.stdout/stderr. This is because StringIO is not a real file object and misses the fileno() function. Commented Nov 16, 2014 at 9:08