pythonprintingpygame

How to block calls to print?


Is there a way to stop a function from calling print?


I am using the pygame.joystick module for a game I am working on.

I created a pygame.joystick.Joystick object and in the actual loop of the game call its member function get_button to check for user input. The function does everything I need it to do, but the problem is that it also calls print, which slows down the game considerably.

Can I block this call to print?


Solution

  • Python lets you overwrite standard output (stdout) with any file object. This should work cross platform and write to the null device.

    import sys, os
    
    # Disable
    def blockPrint():
        sys.stdout = open(os.devnull, 'w')
    
    # Restore
    def enablePrint():
        sys.stdout = sys.__stdout__
    
    
    print 'This will print'
    
    blockPrint()
    print "This won't"
    
    enablePrint()
    print "This will too"
    

    If you don't want that one function to print, call blockPrint() before it, and enablePrint() when you want it to continue. If you want to disable all printing, start blocking at the top of the file.