write() not called when subclassing code.InteractiveInterpreter
Question: When subclassing code.InteractiveInterpreter I can't seem to get the write()
method to run as I would expect per the
[documentation](http://docs.python.org/2/library/code.html).

    
    
    import code
    
    class PythonInterpreter(code.InteractiveInterpreter):
        def __init__(self, localVars):
            self.runResult = ''
            print 'init called'
            code.InteractiveInterpreter.__init__(self, localVars)
    
        def write(self, data):
            print 'write called'
            self.runResult = data
    
    test = 'Hello'
    interpreter = PythonInterpreter({'test':test})
    interpreter.runcode('print test')
    print 'Result:' + interpreter.runResult
    

Expected output:

    
    
    init called
    write called
    Result: Hello
    

Actual output:

    
    
    init called
    Hello   <- shouldn't print
    Result: 
    

Any thoughts?


Answer: The write method is not used by the code passed to runcode at all. You would
have to redirect stdout for this to work, e.g. something like:

    
    
    import code
    
    class PythonInterpreter(code.InteractiveInterpreter):
        def __init__(self, localVars):
            self.runResult = ''
            print 'init called'
            code.InteractiveInterpreter.__init__(self, localVars)
    
        def write(self, data):
            # since sys.stdout is probably redirected,
            # we can't use print
            sys.__stdout__.write('write called\n')
            self.runResult = data
    
        def runcode(cd):
            # redirecting stdout to our method write before calling code cd
            sys.stdout = self
            code.InteractiveInterpreter.runcode(self,cd)
            # redirecting back to normal stdout
            sys.stdout = sys.__stdout__
    

