用exec执行一段python代码,捕获其所有输出?

用exec执行一段python代码,捕获其所有输出?,python,dynamic,io,exec,Python,Dynamic,Io,Exec,执行一堆python代码(如执行mycode)并将打印到stdout的所有内容捕获到字符串中的好方法是什么?尝试替换默认的sys.stdout,如以下代码段: import sys from StringIO import StringIO buffer = StringIO() sys.stdout = buffer exec "print 'Hello, World!'" #remember to restore the original stdout! sys.stdout = sy

执行一堆python代码(如执行mycode)并将打印到stdout的所有内容捕获到字符串中的好方法是什么?

尝试替换默认的sys.stdout,如以下代码段:

import sys
from StringIO import StringIO

buffer = StringIO()
sys.stdout = buffer

exec "print 'Hello, World!'"

#remember to restore the original stdout!
sys.stdout = sys.__stdout__

print buffer.getvalue()

看看这个答案。在执行时,它将取代标准输出。@Reiner:虽然这个问题的措辞更好,但它基本上是那个问题的重复(那个问题的答案非常棒!)。这个应该关闭并指向那个吗?啊,我想做类似的事情,然后出于某种原因决定它不起作用,但我想不会!