Why can't I restore my redirected stdout?
Donn Cave
donn at u.washington.edu
Thu Jun 8 15:13:57 EDT 2000
Quoth "Raymond Ng Tong Leng" <think2 at pd.jaring.my>:
| 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!
I'm not familiar with sys.__stdout__, maybe someone else knows that one.
If you're on UNIX, you can dup() the file descriptors around underneath
stdout, for this effect. I append an example.
Donn Cave, donn at u.washington.edu
----------------------------------------
import os
import sys
class Outs:
def __init__(self):
self.streams = []
def setdevice(self, filename):
# Open an existing file, like "/dev/null"
fd = os.open(filename, os.O_WRONLY)
self.setfd(fd)
def setfile(self, filename):
# Open a new file.
fd = os.open(filename, os.O_WRONLY|os.O_CREAT, 0660);
self.setfd(fd)
def setfd(self, fd):
ofd = os.dup(1) # Save old stream on new unit.
self.streams.append(ofd)
sys.stdout.flush() # Buffered data goes to old stream.
os.dup2(fd, 1) # Open unit 1 on new stream.
os.close(fd) # Close other unit (look out, caller.)
def unset(self):
# Restore previous output stream.
if self.streams:
sys.stdout.flush()
os.dup2(self.streams[-1], 1)
os.close(self.streams[-1])
del self.streams[-1]
More information about the Python-list
mailing list