"""A quick hack to capture stdout/stderr."""importos,sysclassCapture:def__init__(self,mixed_out_err=False):"Start capture of the Unix-level stdout and stderr."if(nothasattr(os,'tmpfile')ornothasattr(os,'dup')ornothasattr(os,'dup2')ornothasattr(os,'fdopen')):self.dummy=1else:try:self.tmpout=os.tmpfile()ifmixed_out_err:self.tmperr=self.tmpoutelse:self.tmperr=os.tmpfile()exceptOSError:# bah? on at least one Windows boxself.dummy=1returnself.dummy=0# make new stdout/stderr files if neededself.localoutfd=os.dup(1)self.localerrfd=os.dup(2)ifhasattr(sys.stdout,'fileno')andsys.stdout.fileno()==1:self.saved_stdout=sys.stdoutsys.stdout=os.fdopen(self.localoutfd,'w',1)else:self.saved_stdout=Noneifhasattr(sys.stderr,'fileno')andsys.stderr.fileno()==2:self.saved_stderr=sys.stderrsys.stderr=os.fdopen(self.localerrfd,'w',0)else:self.saved_stderr=Noneos.dup2(self.tmpout.fileno(),1)os.dup2(self.tmperr.fileno(),2)defdone(self):"End capture and return the captured text (stdoutfile, stderrfile)."ifself.dummy:importcStringIOreturncStringIO.StringIO(),cStringIO.StringIO()else:os.dup2(self.localoutfd,1)os.dup2(self.localerrfd,2)ifself.saved_stdoutisnotNone:f=sys.stdoutsys.stdout=self.saved_stdoutf.close()else:os.close(self.localoutfd)ifself.saved_stderrisnotNone:f=sys.stderrsys.stderr=self.saved_stderrf.close()else:os.close(self.localerrfd)self.tmpout.seek(0)self.tmperr.seek(0)returnself.tmpout,self.tmperrif__name__=='__main__':# testc=Capture()try:os.system('echo hello')finally:fout,ferr=c.done()print'Output:',`fout.read()`print'Error:',`ferr.read()`