How to suppress console output in Python?

后端 未结 8 1805
北荒
北荒 2020-12-02 22:48

I\'m using Pygame/SDL\'s joystick module to get input from a gamepad. Every time I call its get_hat() method it prints to the console. This is problematic since

相关标签:
8条回答
  • 2020-12-02 23:27

    As Demolishun mentions in an answer to a closed duplicate question, there is a thread talking about this issue. The thread is from August of 2009 and one of the developers says the debug code was left in on accident. I had installed Pygame 1.9.1 from pip and the debug output is still present.

    To get around it for now, I downloaded the source from pygame.org, removed the print statements from src/joystick.c and compiled the code.

    I am on OS X 10.7.5 for what it's worth.

    0 讨论(0)
  • 2020-12-02 23:32

    You can get around this by assigning the standard out/error (I don't know which one it's going to) to the null device. In Python, the standard out/error files are sys.stdout/sys.stderr, and the null device is os.devnull, so you do

    sys.stdout = open(os.devnull, "w")
    sys.stderr = open(os.devnull, "w")
    

    This should disable these error messages completely. Unfortunately, this will also disable all console output. To get around this, disable output right before calling the get_hat() the method, and then restore it by doing

    sys.stdout = sys.__stdout__
    sys.stderr = sys.__stderr__
    

    which restores standard out and error to their original value.

    0 讨论(0)
提交回复
热议问题