views:

2373

answers:

3

I'm using python's ftplib to write a small FTP client, but some of the functions in the package don't return string output, but print to stdout. I want to redirect stdout to an object which I'll be able to read the output from.

I know stdout can be redirected into any regular file with:

stdout = open("file", "a")

But I prefer a method that doesn't uses the local drive.

I'm looking for something like the BufferedReader in Java that can be used to wrap a buffer into a stream.

+2  A: 

Use pipe() and write to the appropriate file descriptor.

http://www.python.org/doc/2.3/lib/os-fd-ops.html

Meredith L. Patterson
+10  A: 
from cStringIO import StringIO

old_stdout = sys.stdout
sys.stdout = mystdout = StringIO()

# blah blah lots of code ...

sys.stdout = old_stdout

# examine mystdout.getvalue()
Ned Batchelder
+1, you don't need to keep a reference to the original `stdout` object, as it is always available at `sys.__stdout__`. See http://docs.python.org/library/sys.html#sys.__stdout__.
Ayman Hourieh
Well, that's an interesting debate. The absolute original stdout is available, but when replacing like this, it's better to use an explicit save as I've done, since someone else could have replaced stdout and if you use __stdout__, you'd clobber their replacement.
Ned Batchelder
+5  A: 

Just to add to Ned's answer above: you can use this to redirect output to any object that implements a write(str) method.

This can be used to good effect to "catch" stdout output in a GUI application.

Here's a silly example in PyQt:

import sys
from PyQt4 import QtGui

class OutputWindow(QtGui.QPlainTextEdit):
def write(self, txt):
    self.appendPlainText(str(txt))

app = QtGui.QApplication(sys.argv)
out = OutputWindow()
sys.stdout=out
out.show()
print "hello world !"
Bethor