Package SloppyCell :: Module Redirector_mod
[hide private]

Source Code for Module SloppyCell.Redirector_mod

 1  import os 
 2  import sys 
 3  import tempfile 
 4   
 5  # Adapted from code by Robert Kern.  
 6  # See http://osdir.com/ml/python.ipython.devel/2005-08/msg00014.html 
 7   
 8  STDOUT = 1 
 9  STDERR = 2 
10   
11 -class Redirector(object):
12 - def __init__(self, fd=STDOUT):
13 self.fd = fd 14 self.started = False
15
16 - def start(self):
17 if not self.started: 18 self.flush() 19 self.tmpfd, self.tmpfn = tempfile.mkstemp() 20 21 self.oldhandle = os.dup(self.fd) 22 os.dup2(self.tmpfd, self.fd) 23 os.close(self.tmpfd) 24 25 self.started = True
26
27 - def flush(self):
28 if self.fd == STDOUT: 29 sys.stdout.flush() 30 elif self.fd == STDERR: 31 sys.stderr.flush()
32
33 - def stop(self):
34 if self.started: 35 self.flush() 36 os.dup2(self.oldhandle, self.fd) 37 os.close(self.oldhandle) 38 tmpr = open(self.tmpfn, 'rb') 39 output = tmpr.read() 40 tmpr.close() # this also closes self.tmpfd 41 try: 42 os.unlink(self.tmpfn) 43 except OSError: 44 pass 45 46 self.started = False 47 return output 48 else: 49 return None
50