Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python sys.stdout and C++ iostreams::cout

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.

like image 930
doetoe Avatar asked Jan 17 '13 15:01

doetoe


1 Answers

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++.

like image 145
cdhowie Avatar answered Sep 19 '22 05:09

cdhowie