Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #36945
| From | Nobody <nobody@nowhere.com> |
|---|---|
| Subject | Re: python sys.stdout and C++ iostreams::cout |
| Date | 2013-01-17 15:35 +0000 |
| Message-Id | <pan.2013.01.17.15.35.26.835000@nowhere.com> |
| Newsgroups | comp.lang.python |
| References | <2699150a-cf67-46ac-b863-34c92bffceaf@googlegroups.com> |
| Organization | Zen Internet |
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().
Back to comp.lang.python | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll 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