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

Cla*_*diu 9 python io dynamic exec

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

vrd*_*rde 11

尝试替换默认的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()
Run Code Online (Sandbox Code Playgroud)