How to log everything that occurs in a Python interactive shell session?

后端 未结 5 1465
小蘑菇
小蘑菇 2021-01-05 09:23

I\'d like to have real-time access to both interpreter input and error and standard output. Preferably this information would be written to a file, so that I can poll the fi

5条回答
  •  悲哀的现实
    2021-01-05 10:07

    I've only tested this in python2.7. I don't have 3 handy.

    import code
    import sys
    
    class Tee(object):
    
      def __init__(self, log_fname, mode='a'):
        self.log = open(log_fname, mode)
    
      def __del__(self):
        # Restore sin, so, se
        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
    
    # Tie the ins and outs to Tee.
    sys.stdout = sys.stderr = sys.stdin = Tee('consolelog.dat', 'w')
    
    console = code.InteractiveConsole()
    console.interact()
    

提交回复
热议问题