views:

176

answers:

3

Hi folks,

I'm having a problem with my python script.

It's printing massive amounts of data on the screen, and I would like to prevent all sorts of printing to screen.


Edit:

The library I'm using is mechanize, and it's printing a LOT of data on screen.

I have set these to false with no luck!

br.set_debug_redirects(False)
br.set_debug_responses(False)
br.set_debug_http(False)

Any ideas?

Help would be amazing and very much appreciated!

+3  A: 

(Based on your 2nd edit)

If you don't want to disable all output, you can try to be specific to mechanize itself. http://wwwsearch.sourceforge.net/mechanize/ provides a snippet, which I've modified (though I'm not sure if it will work):

import logging
logger = logging.getLogger("mechanize")
# only log really bad events
logger.setLevel(logging.ERROR)

When you print something it goes to the screen through the sys.stdout file. You can change this file to any other file (eg, a log file you open) so that nothing is printed to the screen:

import sys
# save the old stdout so you can print later (do sys.stdout = OLD_STDOUT)
OLD_STDOUT = sys.stdout
sys.stdout = open("logfile.txt", 'w')

Of course, if you're talking about some library that you're calling, it may be printing to sys.stderr. Luckily, you can do the exact same thing for this one (continuing from above):

OLD_STDERR = sys.stderr
sys.stderr = open("errorLog.txt", 'w')

Now if, for some reason, you want to completely ignore stdout (or stderr) and never see it again, you can define your own file-like classes that simply discard the objects:

class Discarder(object):
    def write(self, text):
        pass # do nothing
# now discard everything coming out of stdout
sys.stdout = Discarder()

And, to add to the din of possible solutions, here is a solution that works in Unix shells:

# discards all input (change /dev/null to a file name to keep track of output)
python yourScript.py > /dev/null
Daniel G
Thanks for the AMAZING reply! sorry about the True/False typo
RadiantHex
+2  A: 

You may redirect sys.stdout and sys.stderr to a file or any file like object of yours e.g.

class EatLog(object):
    def write(self):
       pass

sys.stdout = EatLog()

but i would not recommend that, simpler option is to use OS level redirection e.g.

python myscript.py > out.log
Anurag Uniyal
cobbal
A: 

you can use the StringIO module, too, instead of rolling your own stdout stream. Occasionally, the stdout needs more than a write method (flush is another common one), which StringIO will handle.

import StringIO
import sys

sys.stdout = StringIO.StringIO()
Brendan Abel