Passing the output of a thread to the caller.

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Wed Apr 16 18:19:37 EDT 2008


En Wed, 16 Apr 2008 16:29:48 -0300, Marlin Rowley  
<marlin_rowley at hotmail.com> escribió:

> I have a thread that I've created from a main program.  I started this  
> thread and passed it a function to execute.  Within this function are  
> 'print' statements.  While they are directly translated to the stdout, I  
> would love to return them back to the program itself and store them in  
> an object.  How would I do this?

Replace sys.stdout with an object that stores the lines printed. (Due to  
the way the print statement works, you should not inherit from file)

class PrintBuffer:
     def __init__(self, stream):
         self._stream = stream
         self.output = []
     def write(self, text):
         self.output.append(text)
         self._stream.write(text)
     def __getattr__(self, name):
         return getattr(self._stream, name)

py> import sys
py> sys.stdout = PrintBuffer(sys.stdout)
py> print "Hello world!"
Hello world!
py> print 2,"*",3,"=",2*3
2 * 3 = 6
py> print >>sys.stderr, sys.stdout.output
['Hello world!', '\n', '2', ' ', '*', ' ', '3', ' ', '=', ' ', '6', '\n']
py>

-- 
Gabriel Genellina




More information about the Python-list mailing list