Burton Samograd <bur...@userful.com> writes: > Terry Reedy <tjre...@udel.edu> writes: > >> On 11/23/2010 3:02 PM, Chris Rebert wrote: >> If you are using print or print(), you can redirect output to the >> StringIO object with >>sfile or file=sfile. I use the latter in a >> custom test function where I normally want output to the screen but >> occasionally want to capture test reports. > > Thanks for the info, but I was looking for a way to collect output > without modifying the original function, similar to > with-output-to-string in some schemes.
Redirecting output like with-output-to-string does is achieved by assigning to sys.stdout. Using contextlib you can make it even closer to with-output-to-string by deploying the actual with statement. Unfortunately python's with cannot return a value, so you must expose the StringIO to the caller. The result is still quite nice: import sys, contextlib, cStringIO @contextlib.contextmanager def output_to_string(): oldout = sys.stdout sys.stdout = cStringIO.StringIO() try: yield sys.stdout finally: sys.stdout = oldout >>> with output_to_string() as out: ... print 'foo' ... print 'bar' ... >>> out.getvalue() 'foo\nbar\n' -- http://mail.python.org/mailman/listinfo/python-list