How to suppress console output in Python?

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

    To complete charles's answer, there are two context managers built in to python, redirect_stdout and redirect_stderr which you can use to redirect and or suppress a commands output to a file or StringIO variable.

    import contextlib
    
    with contextlib.redirect_stdout(None):
        do_thing()
    

    For a more complete explanation read the docs

    A quick update: In some cases passing None might raise some reference errors (e.g. keras.models.Model.fit calls sys.stdout.write which will be problematic), in that case pass an io.StringIO() or os.devnull.

提交回复
热议问题