簡體   English   中英

用exec執行一段python代碼,捕獲它的所有輸出?

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

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM