@contextmanager
def capture_stderr():
 s = StringIO()
 (saved, sys.stderr) = (sys.stderr, s)
 try:
  (yield s.getvalue)
 finally:
  sys.stderr = saved

@ contextmanager def capture_stderr ( ) : s = StringIO ( ) ( saved , sys . stderr ) = ( sys . stderr , s ) try : ( yield s . getvalue ) finally : sys . stderr = saved
context manager to capture stderr .