Skip to content

Commit

Permalink
Merge pull request sympy#1168 from smichr/capture
Browse files Browse the repository at this point in the history
capture restores stdout even if function func() fails
  • Loading branch information
goodok committed Mar 25, 2012
2 parents 22951cf + d1da4ac commit 3400a17
Showing 1 changed file with 10 additions and 3 deletions.
13 changes: 10 additions & 3 deletions sympy/utilities/iterables.py
Expand Up @@ -443,23 +443,30 @@ def numbered_symbols(prefix='x', cls=None, start=0, *args, **assumptions):
def capture(func):
"""Return the printed output of func().
`func` should be an argumentless function that produces output with
`func` should be a function without arguments that produces output with
print statements.
>>> from sympy.utilities.iterables import capture
>>> from sympy import pprint
>>> from sympy.abc import x
>>> def foo():
... print 'hello world!'
...
>>> 'hello' in capture(foo) # foo, not foo()
True
>>> capture(lambda: pprint(2/x))
'2\\n-\\nx\\n'
"""
import StringIO
import sys

stdout = sys.stdout
sys.stdout = file = StringIO.StringIO()
func()
sys.stdout = stdout
try:
func()
finally:
sys.stdout = stdout
return file.getvalue()

def sift(expr, keyfunc):
Expand Down

0 comments on commit 3400a17

Please sign in to comment.