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

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


Yes, you can redirect sys.stdout:

import sysimport osold_stdout = sys.stdout # backup current stdoutsys.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


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):       passsys.stdout = NullIO()my_nasty_function()sys.stdout = sys.__stdout__

.


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

from contextlib import redirect_stdoutfrom io import StringIO class NullIO(StringIO):    def write(self, txt):        passdef silent(fn):    """Decorator to silence functions."""    def silent_fn(*args, **kwargs):        with redirect_stdout(NullIO()):            return fn(*args, **kwargs)    return silent_fndef 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())