Path: csiph.com!v102.xanadu-bbs.net!xanadu-bbs.net!feeder.erje.net!eu.feeder.erje.net!zen.net.uk!dedekind.zen.co.uk!reader02.nrc01.news.zen.net.uk.POSTED!not-for-mail From: Nobody Subject: Re: python sys.stdout and C++ iostreams::cout Date: Thu, 17 Jan 2013 15:35:27 +0000 User-Agent: Pan/0.14.2 (This is not a psychotic episode. It's a cleansing moment of clarity.) Message-Id: Newsgroups: comp.lang.python References: <2699150a-cf67-46ac-b863-34c92bffceaf@googlegroups.com> MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Lines: 40 Organization: Zen Internet NNTP-Posting-Host: 0027001e.news.zen.co.uk X-Trace: DXC=Y2M6[AIiS7BTHJl0YRfECG]G;bfYi23hD=dR0\ckLKG@WeZ<[7LZNRFR0H@fGOYQ9ENQ<`Sf8^TaOeD4Zd@TN`?AO^>2jRX?:UI X-Complaints-To: abuse@zen.co.uk Xref: csiph.com comp.lang.python:36945 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().