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.
Use
pipe()
and write to the appropriate file descriptor.https://docs.python.org/library/os.html#file-descriptor-operations
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:
In Python3.6, the
StringIO
andcStringIO
modules are gone, you should useio.StringIO
instead.So you should do this like the first answer:Starting with Python 2.6 you can use anything implementing the
TextIOBase
API from the io module as a replacement. This solution also enables you to usesys.stdout.buffer.write()
in Python 3 to write (already) encoded byte strings to stdout (see stdout in Python 3). UsingStringIO
wouldn't work then, because neithersys.stdout.encoding
norsys.stdout.buffer
would be available.A solution using TextIOWrapper:
This solution works for Python 2 >= 2.6 and Python 3.
Please note that our new
sys.stdout.write()
only accepts unicode strings andsys.stdout.buffer.write()
only accepts byte strings. This might not be the case for old code, but is often the case for code that is built to run on Python 2 and 3 without changes, which again often makes use ofsys.stdout.buffer
.You can build a slight variation that accepts unicode and byte strings for
write()
:You don't have to set the encoding of the buffer the sys.stdout.encoding, but this helps when using this method for testing/comparing script output.
There is contextlib.redirect_stdout() function in Python 3.4:
Here's code example that shows how to implement it on older Python versions.