I'm looking for a function that would silence any prints, so for example this line would do nothing:
silence(print('hello'))
I'm looking for a function that would silence any prints, so for example this line would do nothing:
silence(print('hello'))
This cannot silence the print because print
is executed before silence
:
silence(print('hello'))
On the other hand, you could do this:
@contextlib.contextmanager
def silence():
sys.stdout, old = io.StringIO(), sys.stdout
try:
yield
finally:
sys.stdout = old
with silence():
print('hello')
All the prints are redirected to an io.StringIO
object while in the silence()
context.
You may also choose to do something with the collected prints at the end of the context.