#
__version__ = '$Id: stdoutfilter.py,v 1.4 2002/06/21 06:45:22 hooft Exp $'
#
# Filter stdout and stderr to prevent I/O errors on stdout.
# Some people background programs that are producing output on STDOUT
# or STDERR. If they close the terminal window after that, the
# tty becomes unavailable, and the program might crash when it tries
# to write there. Since the stack trace goes to stderr.....
#
# This module replaces stdout and stderr by pseudo-files
# that will start writing to a file when IOErrors occur on the tty.
#
# User interface:
#     just import this module.
#
# (C) Rob W.W. Hooft, Nonius BV, 1998--2002
#
# Contact rob@hooft.net for questions/suggestions.
# See: <http://starship.python.net/crew/hooft/>
# Distribute freely.
#
import sys,time

class OutputFilefilter:
    def __init__(self,file,altfilename):
	self.file=file
	self.altfilename=altfilename

    def write(self,text):
	if not self.file:
	    return
	try:
	    self.file.write(text)
	except IOError:
	    try:
		self.file=open(self.altfilename,'a')
		self.file.write('===Alternate file opened %s\n'%time.ctime(time.time()))
		self.file.write(text)
	    except IOError:
		self.file=None

    def flush(self):
	if not self.file:
	    return
	try:
	    self.file.flush()
	except IOError:
	    try:
		self.file=open(self.altfilename,'a')
		self.file.write('===Alternate file opened %s\n'%time.ctime(time.time()))
		self.file.flush()
	    except IOError:
		self.file=None
        

sys.stderr=OutputFilefilter(sys.stderr,'stderr.altlog')
sys.stdout=OutputFilefilter(sys.stdout,'stdout.altlog')


