-1

I'm looking for a function that would silence any prints, so for example this line would do nothing:

silence(print('hello'))
martineau
  • 119,623
  • 25
  • 170
  • 301

1 Answers1

2

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.

zvone
  • 18,045
  • 3
  • 49
  • 77
  • 2
    Good answer, although I would suggest redirecting the output to [`os.devnull`](https://docs.python.org/3/library/os.html#os.devnull) which would simply throw it away an not incur the overhead of storing it in memory. – martineau Jul 23 '20 at 00:36
  • @martineau I agree. If the data is not needed, it is better to just throw it away immediately. – zvone Jul 23 '20 at 09:29