How to suppress console output in Python?

后端 未结 8 1803
北荒
北荒 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: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.

提交回复
热议问题