Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ignoring certain print statements based on substring

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
like image 207
Outstretched Pupil Avatar asked Oct 28 '25 08:10

Outstretched Pupil


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()
like image 194
wim Avatar answered Oct 29 '25 23:10

wim



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!