Cactching Stdout

Stephan Kuhagen nospam at domain.tld
Thu Nov 9 06:37:59 CET 2006

Dennis Lee Bieber wrote:

>> this what I need? How can I use them? It is very important
>> for me that I could take the output in real-time.
>> Thanks for the help!
>> Massi
> That's going to be difficult... popen and pipes work when one
> process starts another INDEPENDENT process.

I'm not sure, if it fits the problem, but just a few days ago I had the
problem to catch the stdout and stderr of a module to process it before
writing it to the console. What I did was basically this:

import sys
import StringIO

# save the original streams
_stdout_ = sys.stdout
_stderr_ = sys.stderr

# create StringIO string buffers to replace streams
sys.stdout = StringIO.StringIO()
sys.stderr = StringIO.StringIO()

# Now print something, this goes to the string buffers instead of console
print "Hello World to stdout"
sys.stderr.write("Hello World to stderr\n")

# Now process the contents of the buffers...
# ...and print them to the real console afterwards

# Clean up the string buffers for the next IO

Of course you should put all that into defs and create own write/print
functions to encapsulate the whole buffering/processing/cleanup.

This works great for scripting, but I'm pretty sure, that it does not work
for C Libraries in Python. But I do not know, how Python handles its
streams internally, so it might be worth a try.


More information about the Python-list mailing list