To prevent a function from printing in the batch console in Python

21,768

Solution 1

Yes, you can redirect sys.stdout:

import sys
import os

old_stdout = sys.stdout # backup current stdout
sys.stdout = open(os.devnull, "w")

my_nasty_function()

sys.stdout = old_stdout # reset old stdout

Just replace my_nasty_function with your actual function.

EDIT: Now should work on windows aswell.

EDIT: Use backup variable to reset stdout is better when someone wraps your function again

Solution 2

Constantinius' answer answer is ok, however there is no need to actually open null device. And BTW, if you want portable null device, there is os.devnull.

Actually, all you need is a class which will ignore whatever you write to it. So more portable version would be:

class NullIO(StringIO):
    def write(self, txt):
       pass

sys.stdout = NullIO()

my_nasty_function()

sys.stdout = sys.__stdout__

.

Solution 3

Another option would be to wrap your function in a decorator.

from contextlib import redirect_stdout
from io import StringIO 

class NullIO(StringIO):
    def write(self, txt):
        pass


def silent(fn):
    """Decorator to silence functions."""
    def silent_fn(*args, **kwargs):
        with redirect_stdout(NullIO()):
            return fn(*args, **kwargs)
    return silent_fn


def nasty():
    """Useful function with nasty prints."""
    print('a lot of annoying output')
    return 42


# Wrap in decorator to prevent printing.
silent_nasty = silent(nasty)
# Same output, but prints only once.
print(nasty(), silent_nasty())

Solution 4

You could use a modified version of this answer to create a "null" output context to wrap the call the function in.

That can be done by just passing os.devnull as the new_stdout argument to the stdout_redirected() context manager function when it's used.

Solution 5

Constantinius' solution will work on *nix, but this should work on any platform:

import sys
import tempfile

sys.stdout = tempfile.TemporaryFile()

# Do crazy stuff here

sys.stdout.close()
#now the temp file is gone
sys.stdout = sys.__stdout__
Share:
21,768
NicoCati
Author by

NicoCati

Updated on October 08, 2020

Comments

  • NicoCati
    NicoCati over 3 years

    Well, the headline seems to me sufficient. I use some function that at some points print something in the console. As I can't modify them, I would like to know if there is a solution to not printing while using these functions.

    Thanks a lot !

    Nico