0

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

nam
  • 3,542
  • 9
  • 46
  • 68

2 Answers2

7

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
RichieHindle
  • 272,464
  • 47
  • 358
  • 399
  • 1
    Very interesting solution. I had to add `def flush(self): pass` to make it work. – furas Jun 27 '13 at 12:51
  • please add `def flush(self): pass` to your solution so I can mark as answered – nam Jun 27 '13 at 13:05
  • This is a hack, not a solution you should put in a deployed application. Do you have the option of doing a search/replace on the other scripts to switch the logging from `print` statements to something using the `logging` module? – Silas Ray Jun 27 '13 at 13:08
  • 1
    @sr2222: As I mentioned in my post, this is just too late to change a bundle of scripts already on prod, I will try to convince the other team about the print statement – nam Jun 27 '13 at 13:27
  • 1
    Yeah, I appreciate your predicament. It's just a case of piling bad code on top of bad code though, setting up another potential landmine for future developers trying to reuse your code, or even make modifications to the other code, since you are globally redefining stdout. – Silas Ray Jun 27 '13 at 14:00
2

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
Community
  • 1
  • 1
nemo
  • 55,207
  • 13
  • 135
  • 135