在子类化code.InteractiveInterpreter时不调用write()

时间:2013-02-02 07:51:50

标签: python console

当继承code.InteractiveInterpreter时,我似乎无法按照documentation的预期运行write()方法。

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

预期产出:

init called
write called
Result: Hello

实际输出:

init called
Hello   <- shouldn't print
Result: 

有什么想法吗?

1 个答案:

答案 0 :(得分:3)

传递给runco​​de的代码根本不使用write方法。您必须重定向stdout才能使其正常工作,例如类似的东西:

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__