Cactching Stdout

Stephan Kuhagen nospam at domain.tld
Thu Nov 9 00:37:59 EST 2006


Dennis Lee Bieber wrote:

>> popen...is 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
_stdout_.write(sys.stdout)
_stderr_.write(sys.stderr)

# Clean up the string buffers for the next IO
sys.stdout.truncate(0)
sys.stderr.truncate(0)
---

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.

Regards
Stephan



More information about the Python-list mailing list