Reputation: 3632
I use a internal library that prints a lot (one script could print 40000 lines in total), and I suppose it may have bad impact in performance. This is a library developed by another team in my company and do a lot of calculations, they print to debug errors (and I know this is not a good habit but it's too late because of 100 scripts already on production) and I'm developing a script that uses 100 scripts to produce the result.
How can I decide to turn all this print off ?
I'm not asking how to print these lines to file, but completely omit it
Upvotes: 0
Views: 774
Reputation: 281685
Replace sys.stdout
with an object that eats the output:
import sys
class Null:
def write(self, text):
pass
def flush(self):
pass
print "One" # This gets output OK
old_stdout = sys.stdout
sys.stdout = Null()
print "Two" # This disappears
sys.stdout = old_stdout
print "Three" # Output, back to normal
Upvotes: 7
Reputation: 57709
The best way is to simply remove the print statements as there is no overhead whatsoever.
Alternatively, you can redirect the output to /dev/null
, which will
effectively remove the I/O overhead but will not remove the syscall.
To spare the syscall you can replace sys.stdout
with a Writer which does nothing.
For example:
class NullWriter():
def write(self, s): pass
sys.stdout = NullWriter()
Apparently, this has been asked and solved before. Also here.
In case you're using python 3, you can overload the print
function as
seen in this answer:
def print(*args, **kwargs):
pass
Upvotes: 2