Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 835
NicoCati Avatar asked Dec 09 '11 14:12

NicoCati


People also ask

How do you make a function not print in Python?

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.

How do you skip print in Python?

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 #!

How do I keep the print on the same line in Python?

To print on the same line in Python, add a second argument, end=' ', to the print() function call. print("It's me.")


2 Answers

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

like image 95
Constantinius Avatar answered Oct 04 '22 11:10

Constantinius


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__ 

.

like image 25
vartec Avatar answered Oct 04 '22 11:10

vartec