On Thu, 17 Jan 2013 07:02:24 -0800, 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.
At startup, it refers to the same FILE* as C's stdout. This initially shares a buffer with C++'s std::cout, but that can be changed via std::ios_base::sync_with_stdio(). However ... > 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() This code changes sys.stdout so that it refers to something other than C's stdout. C's stdout is still the same FILE*, C++'s std::count is still the same std::ostream, and the synchronisation between the two hasn't changed. > 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? Changing sys.stdout doesn't (and cannot) have any effect upon how C or C++ code behaves. sys.stdout is just a Python variable. If you want to capture output from C or C++ code, you'll have to do so via other means, e.g. freopen() or dup2(). -- http://mail.python.org/mailman/listinfo/python-list