Temporarily Suppress Console Output in Python

Have you ever wanted to temporarily suppress console output in Python? But you really want it to be temporary, even if an exception happens. Maybe you are calling into some idiot’s library who spams your console. Yeah, that’s happened to me before (maybe I was the idiot–I’m not tellin’).

Here’s a handy way to suppress stdout temporarily in your program:

First, slap this code into your project:

Use it like this:

5 comments to “Temporarily Suppress Console Output in Python”

You can leave a reply or Trackback this post.
  1. can this be used for a HTTP GET output?

  2. http://Johnny says: -#1

    Hi Dave,

    Thanks very much, actually I was looking this exactly. In this case, I am also responsible for the unnecessary output, but that is because I am running other tools into my python tool/script.

    I just want to make you one question, how did you figure out?

    How did you build this code? Where did you take those libraries?

    ( Sorry, I know I said one question but this really interest me :P )

  3. http://Johnny says: -#1

    Hi, I am trying to run your code like this:

    @contextmanager
    def suppress_stdout(ctxm):
    with open(os.devnull, “w”) as devnull:
    old_stdout = sys.stdout
    sys.stdout = devnull
    try:
    yield
    finally:
    sys.stdout = old_stdout

    def testPOLO(self):
    print “You can see this”
    with suppress_stdout():
    print “You cannot see this”
    print “And you can see this again”

    And I am receiving this error message in the function testPOLO:

    “NameError: global name ‘suppress_stdout’ is not defined”

    Do you know why?

  4. This actually does not work when the function is defined outside a class but called inside a class