9
执行一堆python代码(如exec mycode
)并将捕获的所有内容捕获到stdout中的好方法是什么?用exec执行一段python代码,捕获它的所有输出?
执行一堆python代码(如exec mycode
)并将捕获的所有内容捕获到stdout中的好方法是什么?用exec执行一段python代码,捕获它的所有输出?
尝试在这个片段中替换默认的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()
看一看这个答案。 http://stackoverflow.com/questions/3906232/python-get-the-print-output-in-an-exec-statement/3906390#3906390它正在替换执行时间的标准输出。 – 2011-02-05 00:06:47