问题
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.
回答1:
sys.stdout
is a Python object that writes to standard output. It is not actually the standard output file handle; it wraps that file handle. Altering the object that sys.stdout
points to in Python-land does not in any way affect the stdout
handle or the std::cout
stream object in C++.
回答2:
With help from comp.lang.python and after some searching on this site: As cdhowie pointed out, the standard output file handle has to be accessed at a lower level. In fact, its file descriptor can be obtained as sys.stdout.fileno() (which should be 1), and then os.dup and os.dup2 can be used.
I found this answer to a similar question very helpful.
What I really wanted was to capture the output in a string, not a file. The python StringIO class however doesn't have a file descriptor and cannot be used in place of an actual file, so I came up with the not fully satisfactory workaround in which a temporary file is written and subsequently read.
回答3:
It cannot possibly be the same stream, as Python is written in
C, and not C++, and has no 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'd be advised to flush between
writes using the two objects (Python and C++).
来源:https://stackoverflow.com/questions/14382772/python-sys-stdout-and-c-iostreamscout