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
If you don't want that one function to print, call blockPrint() before it, and enablePrint() when you want it to continue. If you want to disable all printing, start blocking at the top of the file.
Search Code Snippets | how to print in python and skip a line. If you want to skip a line, then you can do that with "\n" print("Hello\n World\n!") #It should print: #Hello #World #!
To print on the same line in Python, add a second argument, end=' ', to the print() function call. print("It's me.")
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
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__
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With