embedding: how do I redirect print output?

Steven D'Aprano steve+comp.lang.python at pearwood.info
Tue Jul 5 16:36:43 CEST 2011

Ulrich Eckhardt wrote:

> Hi!
> I'm trying to add some scripting capabilities to an application. Since it
> is a GUI application, I need some way to display output from Python. For
> 3.x, where "print" is a function, I'd just exchange this function with one
> that redirects the output to a log window, right.
> However, I'm using 2.6 here, where that can't work. So, what I was
> thinking was to redirect "sys.stdout" and "sys.stderr" to a log window and
> possibly replace "sys.stdin" with something that causes meaningful errors
> if some code tries to use it, but that last point is just icing on the
> cake.
> What seems cumbersome is that I'll need to write something that supports
> the file interface using C, which is still a bit awkward. I'm wondering,
> isn't there an easier way to achieve this? How would you do it?

Why do you think it needs to be in C? As far as I can tell, so long as it
quacks like a file object (that is, has a write method), it should work.

>>> import StringIO, sys
>>> class Test:
...     def __init__(self):
...             self.out = sys.stdout
...             self.log = StringIO.StringIO()
...     def write(self, text):
...             self.log.write(text.upper())
...             self.out.write(''.join(reversed(text)))
>>> fake_out = Test()
>>> sys.stdout = fake_out
>>> print "Hello world"
dlrow olleH
>>> print "Goodbye cruel world!!!"
!!!dlrow leurc eybdooG
>>> sys.stdout = sys.__stdout__
>>> fake_out.log.getvalue()


More information about the Python-list mailing list