class Tee(object):

    def __init__(self, log_fname, mode='a'):
        self.log = open(log_fname, mode)

def __del__(self):
    sys.stdout = sys.__stdout__
sys.stdir = sys.__stdin__
sys.stderr = sys.__stderr__
self.log.close()

def write(self, data):
    self.log.write(data)
sys.__stdout__.write(data)

def readline(self):
    s = sys.__stdin__.readline()
self.log.write(s)
return s
sys.stdout = sys.stderr = sys.stdin = Tee('consolelog.dat', 'w')
console = code.InteractiveConsole()
console.interact()
How to log everything that occurs in a Python interactive shell session?