python sys.stdout and C++ iostreams::cout
lie.1296 at gmail.com
Fri Jan 18 08:21:47 CET 2013
On 18/01/13 02:02, Utpal Sarkar wrote:
> I was assuming that sys.stdout would be referencing the same physical stream as iostreams::cout running in the same process, but this doesn't seem to be the case.
> The following code, which makes a call to a C++ function with a python wrapper called "write", that writes to cout:
> from cStringIO import StringIO
> import sys
> orig_stdout = sys.stdout
> sys.stdout = stringout = StringIO()
> write("cout") # wrapped C++ function that writes to cout
> print "-" * 40
> print "stdout"
> sys.stdout = orig_stdout
> print stringout.getvalue()
> immediately writes "cout" to the console, then the separator "---...", and finally, as the return value of stringout.getvalue(), the string "stdout".
> My intention was to capture in stringout also the string written to cout from C++.
> Does anyone know what is going on, and if so, how I can capture what is written to cout in a python string?
> Thanks in advance.
You might have a better luck if you check std::ios::rdbuf
Using std::ios::rdbuf() you can get the cout's streambuf, which is a
filebuf for the stdout and then use std::ios::rdbuf(streambuf*) to
replace cout's internal streambuf and replace it with your own
implementation that captures everything written using cout before
passing it back to the original streambuf.
This is essentially similar to assigning to sys.stdout in python.
More information about the Python-list