Python – Temporarily Disable Printing to Console
I had a function I needed to call that insisted on being very verbose and printing a lot of stuff to the console that I didn’t want to see. But the rest of the script printed beautiful things. So the problem was, how can I disable printing ONLY while I call this function?
Here’s what I came up with. It’s primitive but it seems to work.
#Quick, turn off printing! class dummyStream: ''' dummyStream behaves like a stream but does nothing. ''' def __init__(self): pass def write(self,data): pass def read(self,data): pass def flush(self): pass def close(self): pass # Copy old print deals old_printerators=[sys.stdout,sys.stderr,sys.stdin,sys.__stdout__,sys.__stderr__,sys.__stdin__][:] # redirect all print deals sys.stdout,sys.stderr,sys.stdin,sys.__stdout__,sys.__stderr__,sys.__stdin__=dummyStream(),dummyStream(),dummyStream(),dummyStream(),dummyStream(),dummyStream() #call your verbose function here verbose_function() #Turn printing back on! sys.stdout,sys.stderr,sys.stdin,sys.__stdout__,sys.__stderr__,sys.__stdin__=old_printerators
I really just repurposed this recipe: “No print error in console-less environments”. It would be smart to put this whole thing into another function such as “call_without_printing”, and just give that any function you want to run silently.