From b58ea30ba8407abbf9ebe1311fe1586459149308 Mon Sep 17 00:00:00 2001 From: Wirawan Purwanto Date: Fri, 24 Aug 2012 16:31:48 -0400 Subject: [PATCH] * Added a facility to catch exception while capturing stdout, and deliver the output printed so far (to stderr), plus re-raising the exception. --- py/stdout_capture.py | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/py/stdout_capture.py b/py/stdout_capture.py index 482393e..af2aed7 100644 --- a/py/stdout_capture.py +++ b/py/stdout_capture.py @@ -75,12 +75,30 @@ so that the output from sys.stdout is recorded to an ipython log file). #print >> sys.stderr, "calling proc" rslt2 = proc(*args, **argkw) #print >> sys.stderr, "end proc" - finally: + except: #print >> sys.stderr, "finally proc" if needs_stdout_redir: + sys.stdout = StdoutCapture._StdoutCapture_save_stdout + delattr(StdoutCapture, "_StdoutCapture_save_stdout") rslt1 = temp_stdout.getvalue() + temp_stdout.close() + + # clean up the stdout proxy: + if my_stdout_proxy_created: + # delete it so it won't be touched later + delattr(self, "my_stdout_proxy") + if rslt1: + print >> sys.stderr, rslt1 + print >> sys.stderr, "Exception caught while capturing stdout" + raise + + else: + #print >> sys.stderr, "finally proc" + if needs_stdout_redir: sys.stdout = StdoutCapture._StdoutCapture_save_stdout delattr(StdoutCapture, "_StdoutCapture_save_stdout") + print >> sys.stderr, temp_stdout.tell() + rslt1 = temp_stdout.getvalue() #print >> sys.stderr, "stdout redirected back" #sys.stdout.flush() temp_stdout.close()