How to suppress console output in Python?

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

    If you are on a Debian or Ubuntu machine you can just simply recompile pygame without the messages.

    cd /tmp
    sudo apt-get build-dep pygame
    apt-get source pygame
    vim pygame-1.9.1release+dfsg/src/joystick.c
    # search for the printf("SDL.. messages and put a // in front
    apt-get source --compile pygame
    sudo dpkg -i python-pygame_1.9.1release+dfsg-9ubuntu1_amd64.deb
    

    Greetings Max

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

    Building on @charleslparker's answer:

    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
    
    print("Now you see it")
    with suppress_stdout():
        print("Now you don't")
    

    Tests

    >>> with suppress_stdout():
            os.system('play /mnt/Vancouver/programming/scripts/PHASER.WAV')
    
    /mnt/Vancouver/programming/scripts/PHASER.WAV:
    
     File Size: 1.84k     Bit Rate: 90.4k
      Encoding: Unsigned PCM  
      Channels: 1 @ 8-bit    
    Samplerate: 11025Hz      
    Replaygain: off         
      Duration: 00:00:00.16  
    
    In:100%  00:00:00.16 [00:00:00.00] Out:1.79k [!=====|=====!]        Clip:0    
    Done.
    

    Use this to completely suppress os.system() output:

    >>> with suppress_stdout():
            os.system('play /mnt/Vancouver/programming/scripts/PHASER.WAV >/dev/null 2>&1')
    >>> ## successfully executed
    
    >>> import time
    >>> with suppress_stdout():
            for i in range(3):
                    os.system('play /mnt/Vancouver/programming/scripts/PHASER.WAV >/dev/null 2>&1')
                    time.sleep(0.5) 
    >>> ## successfully executed
    
    

    Useful (e.g.) to signal completion of long-running scripts.

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

    Here's the relevant block of code from joystick.c (via SVN at http://svn.seul.org/viewcvs/viewvc.cgi/trunk/src/joystick.c?view=markup&revision=2652&root=PyGame)

        value = SDL_JoystickGetHat (joy, _index);
    #ifdef DEBUG
        printf("SDL_JoystickGetHat value:%d:\n", value);
    #endif
        if (value & SDL_HAT_UP) {
    

    Looks like a problem with having debugging turned on.

    0 讨论(0)
  • 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")
    
    0 讨论(0)
  • 2020-12-02 23:17

    I use pythonw.exe (on Windows) instead of python.exe. In other OSes, you could also redirect output to /dev/nul. And in order to still see my debug output, I am using the logging module.

    0 讨论(0)
  • 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.

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