How to suppress console output in Python?

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 I use the console to help me debug and now it gets flooded with SDL_JoystickGetHat value:0: 60 times every second. Is there a way I can disable this? Either through an option in Pygame/SDL or suppress console output while the function calls? I saw no mention of this in the Pygame documentation.

edit: This turns out to be due to debugging being turned on when the SDL library was compiled.


Here's the relevant block of code from joystick.c (via SVN at

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

Looks like a problem with having debugging turned on.

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 = os.devnull
sys.stderr = os.devnull

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.

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

from contextlib import contextmanager
import sys, os

def suppress_stdout():
    with open(os.devnull, "w") as devnull:
        old_stdout = sys.stdout
        sys.stdout = devnull
            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")

Need Your Help

Timer task does not run

java timer

I am using Timertask in my web application to launch a background thread once every 24 hrs every day at midnight. So I have a ServletContextListener and in contextInitialized, I create a Timertask ...

How do I setup Public-Key Authentication?

linux ssh

How do I setup Public-Key Authentication for SSH?