Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 425
dmlicht Avatar asked Dec 05 '11 20:12

dmlicht


People also ask

How do I block print in Python?

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.

How do you disable stdout in Python?

suppress stdout and stderr with context managerUse suppress_stdout and suppress_stderr flags to indicate which stream to be suppressed. Save the state of the sys. stdout and sys. stderr in the __enter__ function, and redirect them to devnull based on the suppress_stdout and suppress_stderr flags.

What is SYS stdout?

stdout. A built-in file object that is analogous to the interpreter's standard output stream in Python. stdout is used to display output directly to the screen console.

How do you define print in Python?

Definition and UsageThe print() function prints the specified message to the screen, or other standard output device. The message can be a string, or any other object, the object will be converted into a string before written to the screen.


2 Answers

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.

like image 109
Brigand Avatar answered Nov 03 '22 11:11

Brigand


Use with

Based on @FakeRainBrigand solution I'm suggesting a safer solution:

import os, sys  class HiddenPrints:     def __enter__(self):         self._original_stdout = sys.stdout         sys.stdout = open(os.devnull, 'w')      def __exit__(self, exc_type, exc_val, exc_tb):         sys.stdout.close()         sys.stdout = self._original_stdout 

Then you can use it like this:

with HiddenPrints():     print("This will not be printed")  print("This will be printed as before") 

This is much safer because you can not forget to re-enable stdout, which is especially critical when handling exceptions.

Without with — Bad practice

The following example uses enable/disable prints functions that were suggested in previous answer.

Imagine that there is a code that may raise an exception. We had to use finally statement in order to enable prints in any case.

try:     disable_prints()     something_throwing()     enable_prints() # This will not help in case of exception except ValueError as err:     handle_error(err) finally:     enable_prints() # That's where it needs to go. 

If you forgot the finally clause, none of your print calls would print anything anymore.

It is safer to use the with statement, which makes sure that prints will be reenabled.

Note: It is not safe to use sys.stdout = None, because someone could call methods like sys.stdout.write()

like image 22
Alexander C Avatar answered Nov 03 '22 09:11

Alexander C