[英]Execute a block of python code with exec, capturing all its output?
什么是执行一堆python代码的好方法,比如exec 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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.