我假设 sys.stdout 将引用与在同一进程中运行的 iostreams::cout 相同的物理流,但情况似乎并非如此。以下代码使用名为“write”的 python 包装器调用 C++ 函数,并写入 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 的内容?
提前致谢。