python sys.stdout 和 C++ iostreams::cout [英] python sys.stdout and C++ iostreams::cout
问题描述
我假设 sys.stdout 将引用与在同一进程中运行的 iostreams::cout 相同的物理流,但情况似乎并非如此.以下代码使用名为write"的 Python 包装器调用 C++ 函数,并写入 cout:
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()
立即向控制台写入cout",然后是分隔符---...",最后,作为stringout.getvalue() 的返回值,字符串stdout".我的目的是在 stringout 中也捕获从 C++ 写入 cout 的字符串.有谁知道发生了什么,如果是,我如何捕获在 python 字符串中写入 cout 的内容?
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?
提前致谢.
推荐答案
sys.stdout
是一个写入标准输出的 Python 对象.它实际上不是标准输出文件句柄;它包装那个文件句柄.改变 sys.stdout
在 Python-land 中指向的对象不会以任何方式影响 stdout
句柄或 std::cout
流C++ 中的对象.
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++.
这篇关于python sys.stdout 和 C++ iostreams::cout的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!