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

I assumed that sys.stdout would refer to the same physical thread as iostreams :: cout works in the same process, but that doesn't seem to be the case. The following code that calls a C ++ function call with a python shell 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 a string written by cout from C ++. Does anyone know what is going on, and if so, how can I capture what is written in cout in a python string?

Thanks in advance.

+4
source share
3 answers

sys.stdout is a Python object that writes to standard output. This is not a standard output file descriptor; it wraps this file descriptor. Changing the object that sys.stdout points to Python-land in no way affects the stdout handle or the stream object std::cout in C ++.

+6
source

Using comp.lang.python and after some searching on this site: As cdhowie noted, the standard output file descriptor should be available at a lower level. In fact, its file descriptor can be obtained as sys.stdout.fileno () (which should be 1), and then you can use os.dup and os.dup2.

I found this answer to a very close question.

I really wanted to write the output to a string, not a file. However, the python class StringIO does not have a file descriptor and cannot be used instead of the actual file, so I came up with a not completely satisfactory workaround in which a temporary file is written and subsequently read.

+2
source

It cannot be the same thread as Python C, not C ++ and does not have access to std::cout . Whether it uses stdout or implements its own stream based on fd 1, I don’t know, but in any case you are advised to reset writes using two objects (Python and C ++).

+1
source

All Articles