How to suppress console output in Python?

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

    Just for completeness, here's a nice solution from Dave Smith's blog:

    from contextlib import contextmanager
    import sys, os
    
    @contextmanager
    def suppress_stdout():
        with open(os.devnull, "w") as devnull:
            old_stdout = sys.stdout
            sys.stdout = devnull
            try:  
                yield
            finally:
                sys.stdout = old_stdout
    

    With this, you can use context management wherever you want to suppress output:

    print("Now you see it")
    with suppress_stdout():
        print("Now you don't")
    

提交回复
热议问题