Is there a way in Python to silence stdout without wrapping a function call like following?
Original Broken Code:
from sys import stdout
from copy import copy
save_stdout = copy(stdout)
stdout = open('trash','w')
foo()
stdout = save_stdout
Edit: Corrected code from Alex Martelli
import sys
save_stdout = sys.stdout
sys.stdout = open('trash', 'w')
foo()
sys.stdout = save_stdout
That way works but appears to be terribly inefficient. There has to be a better way. Any ideas?
Chiming in very late to this with what I thought was a cleaner solution to this problem.
Usage:
redirect_stdout() has been added to contextlib since python 3.4
For python >= 3.4, this should do it: