Why can't I restore my redirected stdout?
andres at corrada.com
andres at corrada.com
Thu Jun 8 15:03:14 EDT 2000
On Fri, Jun 09, 2000 at 01:52:52AM +0800, Raymond Ng Tong Leng wrote:
> I am trying to implement a verbose and quiet mode in my Python script. So I
> wrote the following class:
>
> class Quiet:
> def write(self, data):
> pass
>
> Then I set sys.stdout to Quiet by:
>
> >>> sys.stdout = Quiet()
> >>> print 'hello'
> >>>
>
> 'hello' doesn't come out which is what I want. But, when I tried to restore
> sys.stdout's original settings:
>
> >>> sys.stdout = sys.__stdout__
> >>> print 'hello'
> >>>
>
> 'hello' is not printed either! How do you restore sys.stdout to its original
> settings? Also, I was wondering, are there other ways to suppress
> sys.stdout? I'm just curious whether I could suppress sys.stdout without
> redirecting to a class. It seems to me that I should be able to redirect
> sys.stdout to a null device or something. Thanks!
>
sys.stdout and sys.__stdout__ point to the same object. Save the default
sdtout before you redefine it:
>>> import sys
>>> sys.stdout
<open file '<stdout>', mode 'w' at 80ce940>
>>> sys.__stdout__
<open file '<stdout>', mode 'w' at 80ce940>
>>> default = sys.stdout
>>> class Quiet:
... def write(self, data):
... pass
...
>>> sys.stdout = Quiet()
>>> sys.stdout
>>> print 'hello'
>>> sys.stdout = default
>>> sys.stdout
<open file '<stdout>', mode 'w' at 80ce940>
------------------------------------------------------
Andres Corrada-Emmanuel Email: andres at corrada.com
------------------------------------------------------
More information about the Python-list
mailing list