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.
sys.stdout
is a Python object that writes to standard output. It is not actually the standard output file handle; it wraps that file handle. Altering the object that sys.stdout
points to in Python-land does not in any way affect the stdout
handle or the std::cout
stream object in C++.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With