To Prevent A Function From Printing In The Batch Console In Python
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
classNullIO(StringIO):
defwrite(self, txt):
passdefsilent(fn):
"""Decorator to silence functions."""defsilent_fn(*args, **kwargs):
with redirect_stdout(NullIO()):
return fn(*args, **kwargs)
return silent_fn
defnasty():
"""Useful function with nasty prints."""print('a lot of annoying output')
return42# 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__
Post a Comment for "To Prevent A Function From Printing In The Batch Console In Python"