Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #36977

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

From Lie Ryan <lie.1296@gmail.com>
Subject Re: python sys.stdout and C++ iostreams::cout
Date 2013-01-18 18:21 +1100
References <2699150a-cf67-46ac-b863-34c92bffceaf@googlegroups.com>
Newsgroups comp.lang.python
Message-ID <mailman.612.1358493723.2939.python-list@python.org> (permalink)

Show all headers | View raw


On 18/01/13 02:02, Utpal Sarkar wrote:
> Hi,
>
> 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 
(http://www.cplusplus.com/reference/ios/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.

Back to comp.lang.python | Previous | Next — Previous in thread | Find similar | Unroll thread


Thread

python sys.stdout and C++ iostreams::cout Utpal Sarkar <doetoe@gmail.com> - 2013-01-17 07:02 -0800
  Re: python sys.stdout and C++ iostreams::cout Nobody <nobody@nowhere.com> - 2013-01-17 15:35 +0000
  Re: python sys.stdout and C++ iostreams::cout Chris Angelico <rosuav@gmail.com> - 2013-01-18 02:42 +1100
    Re: python sys.stdout and C++ iostreams::cout Utpal Sarkar <doetoe@gmail.com> - 2013-01-17 07:51 -0800
      Re: python sys.stdout and C++ iostreams::cout Chris Angelico <rosuav@gmail.com> - 2013-01-18 02:54 +1100
    Re: python sys.stdout and C++ iostreams::cout Utpal Sarkar <doetoe@gmail.com> - 2013-01-17 07:51 -0800
  Re: python sys.stdout and C++ iostreams::cout Lie Ryan <lie.1296@gmail.com> - 2013-01-18 18:21 +1100

csiph-web