Ignoring certain print statements based on substring

Viewed 88

I have some function f which calls some library that generates quite a few unnecessary print statements. I cannot simply remove all values printed, as this would make debugging impossible. However there are certain things that are always printed out that I do want to ignore. Say I want to ignore (not display) any lines printed that include a substring 'substring'. Is there a a way to do something along the lines:

def g():
    print('why is this substring being printed')
    return 1
def f():
    print('this should be printed')
    return g()
# now run with magic function
with IgnorePrints(substring='substring'):
    result = f()

Such that if this code is run with IgnorePrints it will only result in:

this should be printed
1 Answers

Using contextlib.redirect_stdout:

import sys
from contextlib import redirect_stdout

class PrintFilter:
    def __init__(self, stream, substring):
        self.stream = stream
        self.substring = substring

    def write(self, txt):
        if self.substring not in txt:
            self.stream.write(txt)


my_filter = PrintFilter(stream=sys.stdout, substring="substring")

with redirect_stdout(my_filter):
    result = f()
Related