Just to add to what others already said, Python 3.4 introduced the contextlib.redirect_stdout context manager. It accepts a file(-like) object to which the output is to be redirected.
Redirecting to /dev/null will suppress the output:
In [11]: def f(): print('noise') In [12]: import os, contextlib In [13]: with open(os.devnull, 'w') as devnull: ....: with contextlib.redirect_stdout(devnull): ....: f() ....: In [14]:
If the wrapped code doesn't write to sys.stdout directly, you can use the simpler
In [15]: with contextlib.redirect_stdout(None): ....: f() ....: In [16]:
This solution can be adapted to be used as a decorator:
import os, contextlib def supress_stdout(func): def wrapper(*a, **ka): with open(os.devnull, 'w') as devnull: with contextlib.redirect_stdout(devnull): return func(*a, **ka) return wrapper @supress_stdout def f(): print('noise') f() # nothing is printed
Another possible and occasionally useful solution that will work in both Python 2 and 3 is to pass /dev/null as an argument to f and redirect the output using the file argument of the print function:
In [14]: def f(target): print('noise', file=target) In [15]: with open(os.devnull, 'w') as devnull: ....: f(target=devnull) ....: In [16]:
You can even make target completely optional:
def f(target=sys.stdout): # Here goes the function definition
Note, you'll need to
from __future__ import print_function
in Python 2.