0

当子类化 code.InteractiveInterpreter 时,我似乎无法按照文档中的预期运行 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: 

有什么想法吗?

4

1 回答 1

3

传递给 runco​​de 的代码根本不使用 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):
        # 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__
于 2013-03-09T13:29:02.700 回答