Stopping a fucntion from printing its output on screen
Steven D'Aprano
steve at REMOVE-THIS-cybersource.com.au
Wed Oct 17 14:41:43 EDT 2007
On Wed, 17 Oct 2007 07:57:04 -0700, sophie_newbie wrote:
> Hi, in my program i need to call a couple of functions that do some
> stuff but they always print their output on screen. But I don't want
> them to print anything on the screen. Is there any way I can disable it
> from doing this, like redirect the output to somewhere else? But later
> on in the program i then need to print other stuff so i'd need to
> re-enable printing too. Any ideas?
If it is your program, then just change your program to not print to the
screen! Instead of writing a function like this:
def parrot():
# This is bad practice!
do_lots_of_calculations()
print "This is a parrot"
write it like this:
def parrot():
# This is good practice
do_lots_of_calculations()
return "This is a parrot"
What's the difference? In the first version, the function parrot()
decides that its result is always printed. In the second version, YOU
decide:
result = parrot()
# now pass the result to something else
do_more_calculations(result)
# or print it
print result
Otherwise, you can do something like this:
import cStringIO
import sys
capture_output = cStringIO.StringIO()
sys.stdout = capture_output
# call the function that always prints
parrot()
# now restore stdout
sys.stdout = sys.__stdout__
but that's a little risky, and I recommend against it unless you have no
other choice.
--
Steven
More information about the Python-list
mailing list