简体   繁体   中英

Execute a block of python code with exec, capturing all its output?

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

Try replacing the default sys.stdout, like in this snippet:

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM