[英]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.